为什么有状态的小部件在 flutter 中定义为两个类? [英] Why are stateful widgets defined as two classes in flutter?
问题描述
我是 flutter/dart 的新手,所以当我尝试制作一个应用程序时,我也试图理解为什么事情会以某种方式出现.在 flutter 文档中有一个有状态小部件的示例代码,如下所示:
I'm new to flutter/dart, so while I try to make an app I also try to understand why things are a certain way. In the flutter docs there is example code of a stateful widget as shown:
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 类可以在其他地方使用,所以最好分开.
Why are they defined with two classes as opposed to one? I'm guessing the State class can be used somewhere else so it was better to be split up.
据我所知,createState()
函数返回一个 State
类型的对象,因此 _YellowBirdState extends State
是有意义的,但是为什么将YellowBird
传入State
的泛型类中呢?我猜这与 Yellowbird
扩展 StatefulWidget
类有关,但不太确定.
From what I understand the createState()
function returns an object of type State
, so having _YellowBirdState extends State
makes sense, but why is YellowBird
passed into the generic class of State
? My guess it has something to do with Yellowbird
extending the StatefulWidget
class but not quite sure.
推荐答案
原因有多种:
小部件是不可变的.由于
StatefulWidget
扩展了Widget
,因此它也必须是不可变的.将声明分成两个类允许StatefulWidget
是不可变的,而State
是可变的.
Widgets are immutable. Since
StatefulWidget
extendsWidget
it therefore must be immutable too. Splitting the declaration into two classes allows bothStatefulWidget
to be immutable andState
to be mutable.
小部件使用语法new MyWidget()
进行实例化.如果我们将两个类合并为一个,new MyWidget()
将在每次父更新时重置状态的所有属性.
Widgets are instantiated using the syntax new MyWidget()
. If we merged both classes into one, new MyWidget()
would reset all the properties of the state every time its parent update.
至于class _MyStatefulState extends State
那是因为 State
类可以使用 this.widget
字段访问它的 Stateful
部分.泛型在这里使该字段类型为 MyStateful
而不仅仅是 StatefulWidget
.因为您可能想要访问 MyStateful
属性.
That is because the State
class can access to it's Stateful
part using the this.widget
field.
The generic is here to make that field of type MyStateful
instead of just StatefulWidget
. As you may want to access MyStateful
properties.
这篇关于为什么有状态的小部件在 flutter 中定义为两个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!