问题描述
我是扑扑/飞镖的新手,所以在尝试制作应用程序时,我还试图理解为什么事情一定存在。在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扩展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.
关于类的解释_MyStatefulState扩展了State< MyStateful>
这是因为 State
类可以使用<$ c $来访问其 Stateful
部分c> this.widget 字段。
通用名称使该字段的类型为 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中定义为两个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!