在Flutter StatefulWidget中为initState内的变量赋值或不赋值之间有什么区别? [英] is there any difference between assigning value to the variable inside of initState or not in Flutter StatefulWidget?

查看:631
本文介绍了在Flutter StatefulWidget中为initState内的变量赋值或不赋值之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在许多示例代码中,我看到了用StatefulWidget声明变量的两种方法。

I saw two ways to declare variables with StatefulWidget in many sample codes.


  1. 用值初始化变量( firstCase

  2. 初始化没有值的变量,并将其分配给initState( secondCase )内的值

  1. initialize variable with value (firstCase)
  2. initialize variable without value and assign to value inside of initState (secondCase)

两者之间有区别吗?
还是在实践中哪个是更好的代码?

Is there any difference between these? Or which one would be better code in practice?

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,
    );
  }
}


推荐答案

如果您可以直接在属性中创建变量初始化,这样做。

If you can create initialise your variable directly in the property, do so. It's better for readability (a single place to look for).

使用 initState 是当您不能直接从其声明中初始化变量时。

The only reason you'll want to use initState is for when you cannot initialise the variable directly from its declaration.

这些情况大部分是:


  • 您的变量取决于 widget context

  • 这取决于 this

  • your variable depends on widget or context
  • it depends on this

例如,如果要创建 AnimationController ,则需要将其传递给 vsync:this 。但是以下内容无法编译:

For example, if you want to create an AnimationController you'll need to pass it vsync: this. But the following won't compile:

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 关键字,然后允许:

Although note that this specific example will soon change as a future version of Dart will introduce the late keyword, which then allows:

class MyState extends State with SingleTickerProviderStateMixin {
  late final myController = AnimationController(
    vsync: this, // OK, not a compile error this time
  );
}

您可能仍需要 initState 用于取决于 widget / 上下文的变量。

You may still need initState for variables that depends on widget/context though.

这篇关于在Flutter StatefulWidget中为initState内的变量赋值或不赋值之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆