setState()不会在flutter中更新值

时间:2020-03-30 21:53:53

标签: flutter dart statefulwidget

问题:根据我发现的其他解决方案,我在build函数之外初始化了变量,但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
}

0 个答案:

没有答案