flutter - 给 initState 内部的变量赋值或不在 Flutter StatefulWidget 中赋值有什么区别?
问题描述
我在许多示例代码中看到了两种使用 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
。
推荐阅读
- postgresql - 无法在 docker compose 中访问 Postgres 容器
- android - 使用 android.tools.lint 执行 JetifyTransform 失败
- jquery - 更改 jquery-steps 上一个按钮颜色
- keras - 在提前停止的情况下,神经网络中的最佳模型权重
- linux - Ubuntu 管道中的 TFVC“撤消未更改”错误
- python - 更新“用户名”字段将用户注销(flask-login - MongoDB) - 类问题?
- php - How to assert unauthenticated?
- python-3.x - Filter dataframe by minimum number of values in groups
- r - Combine ggplotly and ggplot with patchwork?
- javascript - How do I get the variable and Increment to reset?