Dice Roller Game using Flutter

In this article, we will learn how to create a dice roller Game using flutter. What we shall do today is add a button and if we click on it, the dice should roll on the left and right parts. We can achieve this by wrapping the Image Widget in an Elevated Button. Then changing dice images randomly in a callback function which we set to on pressed property of the FlatButton. We will use Stateful Widgets to create our project. Please look more about the Stateful widget.

First of all, we will create a new Flutter app using the flutter create command. I created a project using the flutter create dice_roller command. Then open the project in vs code.

Step1

Create an image folder and add the required images to the folder.

All the dice image in images folder

Step 2

Include the images in the pubspec.yaml file.

Step 3

Now Working with the main.dart file.

Whenever we change the internal state of a State object on the method dice(), we should make the changes in a function that we have passed to setState:

int leftdiceroll =1;
   int rightdiceroll =1;

   void dice(){
     setState(() {
       leftdiceroll =Random().nextInt(6)+1;
       rightdiceroll= Random().nextInt(6)+1;
     });
   }

Next we initialize the value of the left and right dice roll to 1, and we use a Random() method to generate the random number from 1 to 6 for using these we have to import the library named as import 'dart: math';.

  Expanded(child: Image.asset("images/dice$leftdiceroll.png")),
  const SizedBox(
   width: 30.0,
    ),
 Expanded(child: Image.asset("images/dice$rightdiceroll.png")),

Below we have passed the image index to the left and the right of the screen in order to display the image in the screen.

               ElevatedButton(
                child: const Text("Roll Dicer", textScaleFactor: 2,),
                onPressed: (){
                  dice();
                })

Here in the onpressed method we generally passed the method above the build method() which we have made in order to update the UI screen of the app.

Meanwhile, when we run this application in the emulator or device, we should get the UI similar to the screenshot below.

dice Roller in Flutter
dice Roller in Flutter

Get the full snippet from here

Thank you for reading the guide on creating Dice Roller Game Using Flutter.