How do I generate random numbers using Dart?
Let me solve this question with a practical example in the form of a simple dice rolling app that calls 1 of 6 dice face images randomly to the screen when tapped.
first declare a variable that generates random numbers (don't forget to import dart.math). Then declare a variable that parses the initial random number within constraints between 1 and 6 as an Integer.
Both variables are static private in order to be initialized once.This is is not a huge deal but would be good practice if you had to initialize a whole bunch of random numbers.
static var _random = new Random();
static var _diceface = _random.nextInt(6) +1 ;
Now create a Gesture detection widget with a ClipRRect as a child to return one of the six dice face images to the screen when tapped.
GestureDetector(
onTap: () {
setState(() {
_diceface = _rnd.nextInt(6) +1 ;
});
},
child: ClipRRect(
clipBehavior: Clip.hardEdge,
borderRadius: BorderRadius.circular(100.8),
child: Image(
image: AssetImage('images/diceface$_diceface.png'),
fit: BoxFit.cover,
),
)
),
A new random number is generated each time you tap the screen and that number is referenced to select which dice face image is chosen.
I hoped this example helped :)
Dice rolling app using random numbers in dart