June 16, 2020

Design Dice Roll app in flutter

By Mohit Agrawal

Dice Roll app is specially designed for beginners who want to learn the basics of flutter.

dice roll app in flutter

Overview

If you are reading this flutter tutorial then you must be here to learn the flutter basic concepts. Then you are in the right place. In this tutorial, I will be covering the basic flutter widgets like image, label, and button. I will show you how to create a basic Dice Roll app in flutter just by using these basic widgets.

Introduction

Let me show you first what we are going to design. This will make you sure that you are going to invest your time in the right place.

flutter dice roll app demo
This is what you are going to design

As you can see it has only three basic widget and they are:

  • Text widget is used to display the total sum of the dice’s value.
  • Image widget is used to display the dice
  • RaisedButton widget is used to rolling and updating the dice.

Implementation

Let’s start with the design and coding part.

Creation of the new the flutter project

Create a new flutter project and name it ‘flutter_dice_roll_app’. I am using android studio, you can use any supporting IDE.

Check this for Flutter setup in Android Studio.

Importing the assets in flutter project

Before starting with the coding part, let’s quickly import all the six dice face images to the flutter project. To do this we need to tweak the pubspec.yaml file. Open the file and look at the flutter section. You will find that code for assets is commented. Uncomment it as shown in the screenshot below.

flutter dice roll 2

Now create a folder at the root level of the project and name it ‘images’. You need to put all the assets in the ‘images’ folder only. Download the assets from here and paste them in the same folder.

Setting up the widgets

Now open the main.dart and delete the default boilerplate code. After deleting the extra lines of code, the main.dart should look like this.

import 'dart:math';

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage();

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.deepOrangeAccent,
      body: Padding(
        padding: const EdgeInsets.only(bottom: 60),
      )
    );
  }
}

If you run the code at this point then you will get a blank orange view like this.

flutter dice roll app 1

Now we will put the text, label and button widgets one by one.

import 'dart:math';

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage();

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  var imageArray = ['one.png', 'two.png', 'three.png', 'four.png', 'five.png', 'six.png'];
  int randomIntForDiceOne = Random().nextInt(6);
  int randomIntForDiceTwo = Random().nextInt(6);

  @override
  Widget build(BuildContext context) {

    return Scaffold(
        backgroundColor: Colors.deepOrangeAccent,
        body: Padding(
          padding: const EdgeInsets.fromLTRB(21, 50, 21, 50),
          child: Column(
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(bottom: 60),
                child: Text('The sum is: 8',
                  style: TextStyle(
                    fontSize: 20,
                  ),
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  Image.asset('images/one.png', height: 150, width: 150,),
                  Image.asset('images/one.png', height: 150, width: 150,),
                ],
              ),
              Padding(
                padding: const EdgeInsets.only(top: 60),
                child: RaisedButton(onPressed: changeImage,
                  child: Text('Roll Dice'),
                ),
              )
            ],
          ),
        )
    );
  }

  void changeImage() {

  }
}


In the above-updated code for the ‘main.dart’, I have added UI widgets. If notice I have also added three new variables. The ‘imageArray’ is used to store the image names. I will use two random numbers to set the dice face.

int randomIntForDiceOne = Random().nextInt(6);
int randomIntForDiceTwo = Random().nextInt(6);

If you run the app at this point then you will see the proper UI but the functionality will not work because we have not set any logic at the button click event. Let’s do it now.

import 'dart:math';

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage();

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  var imageArray = ['one.png', 'two.png', 'three.png', 'four.png', 'five.png', 'six.png'];
  //var random = new Random();
  int randomIntForDiceOne = Random().nextInt(6);
  int randomIntForDiceTwo = Random().nextInt(6);

  @override
  Widget build(BuildContext context) {

    return Scaffold(
        backgroundColor: Colors.deepOrangeAccent,
        body: Padding(
          padding: const EdgeInsets.fromLTRB(21, 50, 21, 50),
          child: Column(
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(bottom: 60),
                child: Text('The sum is: '+ (randomIntForDiceOne + randomIntForDiceTwo + 2).toString(),
                  style: TextStyle(
                    fontSize: 20,
                  ),
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  Image.asset('images/'+imageArray[randomIntForDiceOne], height: 150, width: 150,),
                  Image.asset('images/'+imageArray[randomIntForDiceTwo], height: 150, width: 150,),
                ],
              ),
              Padding(
                padding: const EdgeInsets.only(top: 60),
                child: RaisedButton(onPressed: changeImage,
                  child: Text('Roll Dice'),
                ),
              )
            ],
          ),
        )
    );
  }

  void changeImage() {
    setState(() {
      randomIntForDiceOne = Random().nextInt(6);
      randomIntForDiceTwo = Random().nextInt(6);
    });
  }
}


As you can see, I am calling a function changeImage() while clicking the button. This function updates the value of both the integer variable with a new random number generated.

Now run the project again see how it is working. If you have done everything right till here then you will find it working. Let me know if you are facing any problem in the comment section.

Subscribe YouTube: More tutorials like this

I hope this blog post is useful for you, do let me know your opinion in the comment section below.
I will be happy to see your comments down below 👏.
Thanks for reading!!!

android android beginners tutorial android tutorial Animation API call API call in iOS async asynchronous cardview custom switch custom ui dark web dark web links deep web deep web links Dynamic gradient view facebook messenger firebase hosting firebase hosting tutorial firebase remote config firebase tutorials flutter flutter for beginner flutter tutorial flutter UI tutorial hacking hacking tutorial hashcat iOS ios tutorial ios ui tutorial kotlin listview in flutter Lottie animation Messenger for kids review onion links Roll the Dice app swift tech news tor tor browser tor links UISwitch wifi wifi hacking