在Flutter StatefulWidget中为initState内的变量赋值或不赋值之间有什么区别?
问题内容:
我在许多示例代码中看到了两种使用StatefulWidget声明变量的方法。
- 用值初始化变量( firstCase )
- 初始化没有值的变量,并将其赋给initState( secondCase )内部的值
这些之间有什么区别吗?或者在实践中哪一个是更好的代码?
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,
);
}
}
问题答案:
如果可以直接在属性中创建变量初始化,请执行此操作。可读性更好(一个地方寻找)。
您要使用的唯一原因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
);
}
而且您不得不写:
class MyState extends State with SingleTickerProviderStateMixin {
AnimationController myController;
@override
void initState() {
super.initState();
myController = AnimationController(
vsync: this, // OK
);
}
}
尽管请注意,随着Dart的未来版本将引入late
关键字,此特定示例将很快更改,该关键字随后将允许:
class MyState extends State with SingleTickerProviderStateMixin {
late final myController = AnimationController(
vsync: this, // OK, not a compile error this time
);
}
您可能仍然需要initState
依赖于widget
/的变量context
。