【发布时间】: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