【问题标题】:Perils of Flutter state in StatefulWidget rather than State?在 StatefulWidget 而不是 State 中 Flutter 状态的危险?
【发布时间】:2020-01-27 05:37:48
【问题描述】:

我了解 StatefulWidget 子类旨在是不可变的,并且我们倾向于将状态存储在 State 子类中。 (这里不讨论高级状态管理技术。)

那么,将我们的模型/状态存储在 StatefulWidget 类而不是 State 类中的危险是什么?既然 State 实例有一个引用 StatefulWidget 的widget 属性,为什么不把状态存储在那里呢?

例如:

class Foo extends StatefulWidget {

  int count = 0; // state

  State createState() => FooState();
}

class FooState extends State<Foo> {

  Widget build(BuildContext context) {
    return Column(children:[
      Text(widget.count.toString()),
      FloatingActionButton(
        onPressed: doIt
      )
    ]);
  }

  void doIt() {
    setState( () {
      widget.count += 1;
    });
  }

}

当 state 是一个对象并传递给 State 实例时,这些担忧是否仍然适用?

例如:

class Foo extends StatefulWidget {

  final counter = Counter(0); // state

  State createState() => FooState(counter);
}

class FooState extends State<Foo> {

  final counter;

  FooState(this.counter);

  Widget build(BuildContext context) {
    return Column(children:[
      Text(counter.stringValue()),
      FloatingActionButton(
        onPressed: doIt
      )
    ]);
  }

  void doIt() {
    setState( () {
      counter.increment();
    });
  }

}

【问题讨论】:

    标签: flutter


    【解决方案1】:

    不变性用于性能原因。如果小部件需要更改,请创建一个相应设置的新实例。检查两个实例是否相同比检查它们的状态是否相同要快。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 2020-12-18
      • 2018-07-06
      • 2019-10-09
      • 2018-12-21
      相关资源
      最近更新 更多