【问题标题】:variable won't change Text dynamically in flutter变量不会在颤动中动态更改文本
【发布时间】:2018-07-21 13:56:12
【问题描述】:

我已经定义了我的应用程序,并将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'),
     ...

我修改了GameRedux里面的counter,我看到了变量的变化,但是它不会影响UI中的Text,为什么库存为零?

【问题讨论】:

  • 您需要调用您要重建的组件的setState(() => counter = newValue)。如果您调用父后代的setState(),也将重建。如果您对后代调用setState(),这不会影响父母 - 这是您正在处理的情况。
  • @GünterZöchbauer 感谢您的回答,对于令人尴尬的请求感到抱歉,但是您能否提供少量示例代码作为答案,以便我接受您?我应该把 setState() 放在哪里?

标签: dart flutter


【解决方案1】:

您必须将您的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,
     ),
     ...

【讨论】:

  • 我设法解决了创建有状态文本并将计数器作为动态变量传递的问题
  • @ShaheenZahedi 让我知道答案是否有帮助。如果没有,我可以删除它。
  • 救了我!非常感谢:)
  • 注意:setState() 在 Flutter 新版本中不能在 build() 中工作。您可以在没有setState() 的情况下简单地为该变量赋值。
猜你喜欢
  • 2019-10-03
  • 2021-10-18
  • 2023-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-14
  • 2021-08-21
  • 2023-01-02
相关资源
最近更新 更多