1

Problem: As per the other solutions I found, I initialized my variable outside the build function but setState() still doesn't update my value.

Here, I am trying to update the value of ldn(left-dice-number) to 6 from 1 when ever it senses a touch. When I print the values on the console, it shows:

I/flutter (29149): LDN = 1
I/flutter (29149): LDN = 6

Here is the code for my stateful widget:

class DicePage extends StatefulWidget {
  @override
  _DicePageState createState() => _DicePageState();
}


class _DicePageState extends State<DicePage> {
  int ldn;
  @override
  Widget build(BuildContext context) {
    ldn = 1;
    return Center(
      child: Row(
        children: <Widget>[
          Expanded(
            child: Padding(
              padding: const EdgeInsets.fromLTRB(16, 16, 8, 16),
              child: FlatButton(
                padding: EdgeInsets.all(0),
                onPressed: (){
                  setState(() {
                    print('LDN = $ldn');
                    ldn = 6;
                    print('LDN = $ldn');
                  });
                },
                child: Image.asset('images/dice$ldn.png'),
              ),
            ),
          ),
          Expanded(
            child:Padding(
              padding: const EdgeInsets.fromLTRB(8, 16, 16, 16),
              child: FlatButton(
                onPressed: (){
                  print('Right buttin got pressde');
                },
                padding: EdgeInsets.all(0),
                child: Image.asset('images/dice1.png'),
              ),
            ),
          )
        ],
      ),
    );
  } // Build
}
Doc
  • 10,831
  • 3
  • 39
  • 63
  • 3
    dont set the value again inside build: make it `int ldn=1;` outside the `build()` – Doc Mar 30 '20 at 22:06
  • 1
    You declared the ldn = 1 at the top of your build function. That's why every time state(basically page) is refreshed with setState, ldn is assigned with value 1. Remove that line. – Zahid Tekbaş Mar 30 '20 at 22:09

1 Answers1

0

The reason why int ldn is always set to 1 is because ldn = 1; is declared inside Widget build(). Calling setState will cause the screen to rebuild, initializing int ldn as 1 again. Initializing the variable outside Widget build should solve the issue.

Omatt
  • 8,564
  • 2
  • 42
  • 144