我在很多示例代码中看到了两种用 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
的唯一原因是当您无法直接从声明中初始化变量时。
这些情况大部分是:
- 您的变量取决于
小部件
或上下文
- 这取决于
这个
例如,如果您想创建一个 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 的 future 版本将引入 late
关键字,从而允许:
class MyState extends State with SingleTickerProviderStateMixin {
late final myController = AnimationController(
vsync: this, // OK, not a compile error this time
);
}
不过,您可能仍然需要 initState
来获取依赖于 widget
/context
的变量。
关于flutter - 在 Flutter StatefulWidget 中给 initState 内部的变量赋值与不给变量赋值有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59611811/