How do I generate random numbers in Dart?

前端 未结 14 1258
一个人的身影
一个人的身影 2021-01-31 06:49

How do I generate random numbers using Dart?

14条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-31 07:20

    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

提交回复
热议问题