为什么有状态的窗口小部件在flutter中定义为两个类?
问题内容:
我不熟悉Flutter / Dart,因此在尝试制作应用程序时,我还尝试理解为什么事情是特定的。在flutter文档中,有状态小部件的示例代码如下所示:
class YellowBird extends StatefulWidget {
const YellowBird({ Key key }) : super(key: key);
@override
_YellowBirdState createState() => new _YellowBirdState();
}
class _YellowBirdState extends State<YellowBird> {
@override
Widget build(BuildContext context) {
return new Container(color: const Color(0xFFFFE306));
}
}
问题:
-
为什么用两个类而不是一个类来定义它们?我猜State类可以在其他地方使用,所以最好拆分。
-
据我了解,该
createState()
函数返回一个类型的对象State
,因此_YellowBirdState extends State
有意义,但是为什么将其YellowBird
传递给的泛型类State
呢?我的猜测与Yellowbird
扩展StatefulWidget
类有关,但不确定。
问题答案:
有多种原因:
-
小部件是不可变的。由于
StatefulWidget
扩展Widget
,因此它也必须是不变的。将声明分为两个类可以使它们既StatefulWidget
不变又State
可变。 -
使用语法实例化窗口小部件
new MyWidget()
。如果我们将两个类合并为一个,new MyWidget()
则每次其父级更新时,都会重置该状态的所有属性。
至于解释 class _MyStatefulState extends State<MyStateful>
那是因为State
该类可以Stateful
使用该this.widget
字段访问它的一部分。泛型在这里使该类型的字段MyStateful
而不是just
StatefulWidget
。您可能要访问MyStateful
属性。