In this example, we are going to show you the simple way to generate random numbers or double values within the minimum and maximum range. See the example below for more details.
See this also: How to Generate Random Color in Flutter
import 'dart:math';
int random = Random().nextInt(1000); //1000 is MAX value
//generate random number below 1000
int randomminmax = min + Random().nextInt(max - min);
//generate random number within minimum and maximum value
double randomdouble = Random().nextDouble();
//generate random double within 0.00 - 1.00;
randomdouble = double.parse(randomdouble.toStringAsFixed(4));
//toStringAsFixed will fix decimal length to 4, 0.3454534 = 0.3454
import 'dart:math';
import 'package:flutter/material.dart';
void main(){
runApp(MyApp());
}
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
);
}
}
class Home extends StatefulWidget{
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
int randomnumber = 0, randomminmax = 0;
double randomdouble = 0.00;
int randomNumber(){
int random = Random().nextInt(1000); //1000 is MAX value
//generate random number below 1000
return random;
}
int randomNumberMinMax(int min, int max){
int randomminmax = min + Random().nextInt(max - min);
//generate random number within minimum and maximum value
return randomminmax;
}
double randomDouble(){
double randomdouble = Random().nextDouble();
//generate random double within 0.00 - 1.00;
return double.parse(randomdouble.toStringAsFixed(4));
//toStringAsFixed will fix decimal length to 4, 0.3454534 = 0.3454
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Random Number"),
backgroundColor: Colors.deepPurpleAccent,
),
body: Container(
height:200,
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: (){
setState(() {
randomnumber = randomNumber();
//call random number generate function
});
},
child: Text("Random Number: $randomnumber")
),
ElevatedButton(
onPressed: (){
setState(() {
randomminmax = randomNumberMinMax(100, 300);
//call random number generate function with min and max
});
},
child: Text("Random Number Min Max: $randomminmax")
),
ElevatedButton(
onPressed: (){
setState(() {
randomdouble = randomDouble();
//call random double value generate function
});
},
child: Text("Random Duouble: $randomdouble")
)
],
)
)
);
}
}
In this way, you can generate random numbers within min and max range, double values using dart in Flutter App.
Please Wait...
No any Comments on this Article