变量不会在颤动中动态更改文本 [英] variable won't change Text dynamically in flutter

查看:59
本文介绍了变量不会在颤动中动态更改文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了我的应用程序,并且将 counter 变量作为如下构造函数传递:

I have my application defined, and I pass counter variable as a constructor like below:

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'),
     ...

我修改计数器 GameRedux 里面,我看到了变量的变化,但是它不会影响UI中的文本,并且为什么库存为零?

I modify the counter inside GameRedux, and I see variable changes, but it will not effect the Text in the UI, and it stocks on zero why?

推荐答案

您必须将 StatelessWidget 小部件设置为 StatefulWidget 因为这是更改 counter 变量状态(使用 setState())时布局的重建方式。如下所示,

You have to make your StatelessWidget widget to StatefulWidget because that is how layout rebuild when state of counter variable changed(using setState()). Your code should look like below,

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,
     ),
     ...

这篇关于变量不会在颤动中动态更改文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆