Home > Enterprise >  Flutter: setState in TextButton not working
Flutter: setState in TextButton not working

Time:02-08

Dice image not changing on onPress
setState not setting dice image for random number

child: Image.asset('images/dice$leftDiceNumber.png'), not working but
child: Image.asset('images/dice2.png'), is working that means hard code is working

var leftDiceNumber = 3; getting only dice3.png as i initialize it for leftDiceNumber

Please help for getting random image when onPress


No errors in App

class DicePage extends StatefulWidget {
  const DicePage({Key? key}) : super(key: key);

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

class _DicePageState extends State<DicePage> {
  @override
  Widget build(BuildContext context) {
    var leftDiceNumber = 3;
    return Center(
      child: Row(
        children: [
          Expanded(
            child: TextButton(
              onPressed: () {
                setState(() {   
                  leftDiceNumber = Random().nextInt(6)   1;
                  print(leftDiceNumber); // getting value in console
                });
              },
              child: Image.asset('images/dice$leftDiceNumber.png'),  
                      //child: Image.asset('images/dice1.png'), // ( works )
            ),),],
      ),);}}

CodePudding user response:

That is because every time you call setState() it calls the build method, and you have defined leftDiceNumber = 3 inside the build method. So even though the setState() changes the value it again gets set to 3.

Solution: Move var leftDiceNumber = 3; outside the build method.

class _DicePageState extends State<DicePage> {
  var leftDiceNumber = 3;
  
@override
  Widget build(BuildContext context) {
    return YourWidget();
  }
}
  •  Tags:  
  • Related