2

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

1 Answer 1

5

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();
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

You should add the initState method and the solution is perfect
If we can initialize variables without doing the following wouldn't it make it simpler? late variableName; and then initState(){variableName = value;} I'm new to flutter. I'm guessing that using initState() is a good practice even if it is for a simple variable like this. Please enlighten me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.