Creating the Dice class

The first screen we will create in the app will show a single dice. When opening the screen, our users will see the dice at the Start position, and a button to play. When they press the button, they will be able to roll the dice, see the Roll animation, and get a random result from 1 to 6. You can see an example of the Single Dice screen in the following screenshot:

Before adding the first screen, let's create a new service class that will contain the methods necessary to get a random number and the names of the animations for the result, as follows:

  1. Create a new file in the lib folder of your project, called dice.dart.
  2. At the top of the new file, import the math library that is needed to generate a random number, as follows:
import 'dart:math';
  1. Create a new class called Dice, as follows:
class Dice {}

  1. In the class, add a static list of animations, called animations. This contains the animations that will be called from the app when the result must be shown, and the code can be seen in the following block:
static List<String> animations = [
'Set1',
'Set2',
'Set3',
'Set4',
'Set5',
'Set6',
];
    1. Create a static method called getRandomNumber() that returns a random number between 1 and 6, as follows:
    static getRandomNumber() {
    var random = Random();
    int num = random.nextInt(5) + 1;
    return num;
    }
    1. Create another static method, returning a Map of type int and a String called getRandomAnimation. The purpose of the method is to generate a random number between 0 and 5 and return a Map containing the number and the name of the animation in the animations list at the position of the number itself. You can see the necessary code in the following snippet:
    static Map<int, String> getRandomAnimation() {
    var random = Random();
    int num = random.nextInt(5);
    Map<int, String> result = {num: animations[num]};
    return result;
    }

    1. The last method of this class, still static, is called wait3seconds(). The purpose of the function, as you might guess, is just waiting 3 seconds. This is the duration we want to give the rolling animation of the dice. You might recall that the original duration of the rolling animation is only 1 second. By waiting for 3 seconds, we will repeat the animation three times, as each one only lasts 1 second.

    Add the following code in the class:

    static Future wait3seconds() {
    return new Future.delayed(const Duration(seconds: 3), () {});
    }

    That completes the Dice class. Now, we'll create the single.dart screen!

    ..................Content has been hidden....................

    You can't read the all page of ebook, please click here login for view all page.
    Reset
    13.59.173.242