如果可以直接在属性中创建变量初始化,请执行此 *** 作。可读性更好(一个地方寻找)。
您要使用的唯一原因
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。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)