Flutter: Update text on screen when MaterialButton is clicked

Question

Asked by Kiran V on November 23, 2021 (source).

I'm new to Flutter. I'm trying to build a basic dice app with a button. When the button is clicked, the displayed text gets updated with a random number.

import 'package:flutter/material.dart';
import 'dart:math';

int dice = 0;

void main() {
  int dice = 0;
  runApp(
    MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.white70,
        appBar: AppBar(
          title: const Text('Quick Dice'),
          backgroundColor: Colors.blueGrey,
        ),
        body: Center(
          child: MaterialButton(
            onPressed: () {
              rollDice();
            },
            child: new Text('$dice'),
          ),
        ),
      ),
    ),
  );
}

void rollDice(){
  dice = Random().nextInt(6) + 1;
  print('In Roll Dice()');
  print('$dice');
}

When the button is clicked, I can see that the function rollDice() is being called and the value of $dice is being updated but on the screen, the value never gets updated.

Is there something I'm missing? Should the child text element be refreshed somehow to to show the new value on button press?

Answer

Question answered by Mojtaba G (source).

Do like this ( StatefulWidget ) :

void main(){
  runApp(MaterialApp(
    home: UpdateScreen(),
  ));
}

class UpdateScreen extends StatefulWidget{
  @override
  UpdateScreenState createState() => UpdateScreenState();

}

class UpdateScreenState extends State<UpdateScreen>{

  int dice = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white70,
      appBar: AppBar(
        title: const Text('Quick Dice'),
        backgroundColor: Colors.blueGrey,
      ),
      body: Center(
        child: MaterialButton(
          onPressed: () {
            rollDice();
          },
          child: new Text('$dice'),
        ),
      ),
    );
  }

  void rollDice(){
    setState(() {
      dice = Random().nextInt(6) + 1;
      print('In Roll Dice()');
      print('$dice');
    });
  }

}
DART FLUTTER
SHARE: