1

问题:根据我找到的其他解决方案,我在构建函数之外初始化了我的变量,但 setState() 仍然没有更新我的值。

在这里,我尝试在感应到触摸时将 ldn(left-dice-number) 的值从 1 更新为 6。当我在控制台上打印值时,它显示:

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

这是我的有状态小部件的代码:

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
}
4

0 回答 0