我在许多示例代码中看到了两种使用 StatefulWidget 声明变量的方法。
这些有什么区别吗?或者哪一个在实践中是更好的代码?
class Sample extends StatefulWidget {
Sample({Key key}) : super(key: key);
@override
_SampleState createState() => _SampleState();
}
class _SampleState extends State<Sample> {
bool firstCase = false;
bool secondCase;
@override
void initState() {
secondCase = false;
super.initState();
}
@override
Widget build(BuildContext context) {
return Container(
child: child,
);
}
}
Run Code Online (Sandbox Code Playgroud)
Rém*_*let 19
如果您可以直接在属性中创建初始化您的变量,请这样做。可读性更好(寻找一个地方)。
您要使用的唯一原因initState
是当您无法直接从其声明中初始化变量时。
这些情况大部分是:
widget
或context
this
例如,如果你想创建一个,AnimationController
你需要传递它vsync: this
。但以下不会编译:
class MyState extends State with SingleTickerProviderStateMixin {
final myController = AnimationController(
vsync: this, // compile error, cannot use `this` on initialisers
);
}
Run Code Online (Sandbox Code Playgroud)
而你必须改为写:
class MyState extends State with SingleTickerProviderStateMixin {
AnimationController myController;
@override
void initState() {
super.initState();
myController = AnimationController(
vsync: this, // OK
);
}
}
Run Code Online (Sandbox Code Playgroud)
尽管请注意,这个特定示例很快就会改变,因为 Dart 的未来版本将引入late
关键字,然后允许:
class MyState extends State with SingleTickerProviderStateMixin {
late final myController = AnimationController(
vsync: this, // OK, not a compile error this time
);
}
Run Code Online (Sandbox Code Playgroud)
您可能仍然需要initState
依赖于widget
/ 的变量context
。
归档时间: |
|
查看次数: |
877 次 |
最近记录: |