Skip to content
Related Articles

Related Articles

Improve Article

Flutter – Dice Roller App

  • Difficulty Level : Hard
  • Last Updated : 08 Jan, 2021

Here we will be building a simple dice app that rolls on click. For this, we will add a button and when we click on it the dice should roll. We can achieve this by wrapping Image Widget in a FlatButton Widget and changing dice images randomly in a callback function which is set to onPressed property of the FlatButton

We will create this app using Stateful Widgets. Stateful Widgets are the ones that change its properties during run-time. They are dynamic i.e., they are mutable and can be drawn multiple times within its lifetime. It can change its appearance in response to events triggered by user interactions or when it receives data like Checkbox, Radio Button, Slider, InkWell, Form and TextField.

Do the initial setup for Flutter Development and create a project. Now, follow the below steps to build the app.

Step 1: Create an image folder and add the required images in the folder.

Add dice images in images folder

Add dice images in images folder

Step 2: Include the images in the pubspec.yaml file.



flutter:
  uses-material-design: true
  assets:
  - images/

Note: Use proper indentation in pubspec.yaml.

Step 4: Working with the main.dart file.

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

setState(() { myState = newValue; });

Go to the main.dart file and refer to the following code. Below is the code for the main.dart file.

Dart




import 'package:flutter/material.dart';
import 'dart:math';
 
void main() {
  return runApp(
    MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.black,
        appBar: AppBar(
          title: Text('GFG | Dice'),
          backgroundColor: Color.fromRGBO(15, 157, 88, 1),
        ),
        body: Dice(),
      ),
    ),
  );
}
 
class Dice extends StatefulWidget {
  @override
  _DiceState createState() => _DiceState();
}
 
class _DiceState extends State<Dice> {
  int dice_no = 1;
  void update() {
    setState(() {
      //Random.nextInt(n) returns random integer from 0 to n-1
      dice_no = Random().nextInt(6) + 1;
    });
  }
 
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Expanded(
        child: Padding(
          padding: const EdgeInsets.all(50.0),
          child: FlatButton(
            child: Image.asset('images/dice$dice_no.png'),
            onPressed: () {
              update();
            },
          ),
        ),
      ),
    );
  }
}

Output:

Note : You can download the required images from here.




My Personal Notes arrow_drop_up
Recommended Articles
Page :