变量不会在颤动中动态更改文本

2023-12-07

我已经定义了我的应用程序,并且通过了counter变量作为构造函数,如下所示:

class AppThreePlusThree extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var game = new Game();
    var counter = 265;
    return new GameRedux(
      counter: counter,
      child: new MaterialApp(
        title: '3 + 3',
        theme: new ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: new Scaffold(
     ...
     ...
     new Text('$counter'),
     ...

我修改counter inside GameRedux,我看到变量发生变化,但它不会影响用户界面中的文本,并且它的库存为零,为什么?


你必须让你的StatelessWidget小部件到StatefulWidget因为这就是当状态为时重建布局的方式counter变量改变(使用setState())。您的代码应如下所示,

class AppThreePlusThree extends StatefulWidget {
  _AppThreePlusThreeState createState() => _AppThreePlusThreeState ();
}

class _AppThreePlusThreeState extends State<AppThreePlusThree> {
  var counter = 265;
  var counter2 = 265;

  void changeVariableOnUI() {
    setState(() => counter2 = 22); 
  }

  @override
  Widget build(BuildContext context) {
    var game = new Game();
    // Inside the build method you cannot (no need) use setState but outside the build() to update a variable value on the UI have to use setState
    counter = 265; //I seriously doesnt have any idea how you are going to change or update your counter variable. something like this should work
    return new GameRedux(
      counter: counter,
      child: new MaterialApp(
        title: '3 + 3',
        theme: new ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: new Scaffold(
     ...
     ...
     Text('$counter'),
     Text('$counter2'),
     InkWell(
       child: Text("Tap here"),
       onTap: changeVariableOnUI,
     ),
     ...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

变量不会在颤动中动态更改文本 的相关文章