简体   繁体   中英

Flutter: setState in TextButton not working

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 ) ),),], ),);}}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM