首页 > 解决方案 > 给 initState 内部的变量赋值或不在 Flutter StatefulWidget 中赋值有什么区别?

问题描述

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

  1. 用值初始化变量(firstCase
  2. 初始化没有值的变量并分配给 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,
    );
  }
}

标签: flutterdart

解决方案


如果您可以直接在属性中创建初始化变量,请执行此操作。更好的可读性(一个寻找的地方)。

您要使用的唯一原因initState是当您无法直接从其声明中初始化变量时。

这些情况大部分是:

  • 您的变量取决于widgetcontext
  • 这取决于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


推荐阅读