Home > Blockchain >  Flutter: Update text on screen when MaterialButton is clicked
Flutter: Update text on screen when MaterialButton is clicked

Time:11-23

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?

CodePudding user response:

Your method is working find but value is not updating in the UI cause you are not Using Set State anywhere in your app. Just create a separate Stateful widget for your app body and in onPressed also call the setState method to get your UI updated.

CodePudding user response:

For updating your data on screen you have to use state management like provider, Getx , block etc. Or you can use the setState method in your rollDice() function then the the widget will rebuild and your data will be updated. Something like this--

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

CodePudding user response:

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');
    });
  }

}

CodePudding user response:

Try below code hope its helpful to you.

Refer Random enter image description here | enter image description here

  • Related