我在许多示例代码中看到了两种使用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,
    );
  }
}

推荐答案

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

您希望使用initState的唯一原因是,当您cannot直接从变量声明初始化变量时.

这些情况在很大程度上是:

  • 您的变量取决于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的future 版本将引入late关键字,这将允许:

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

但是,对于依赖于widget/context的变量,您可能仍然需要initState.

Dart相关问答推荐

polymer.dart 中的@observable 和@published 有什么区别?

修复了 Flutter Dart 上 DataTable 的列和行标题

自定义主题无法正常工作

如何在 Dart 游戏中重复听按键?

在Flutter中实现像Chanel app一样的自定义滚动?

Flutter中包导入和普通导入有什么区别?

Flutter:合并两张图片,作为单张图片存储在本地存储中

如何在 ListView 中添加额外的底部间距?

在 Dart 中将对象推入数组

无法导入 dart 的 intl 包

在 Flutter 中推送新页面时,Navigator 堆栈上的页面会重建

Flutter /dart 错误:参数类型'Future'不能分配给参数类型'File'

在 Flutter 的 TextFormField 中管理事件

谷歌的 Dart 编程语言的作用是什么?

可以在 Dart 中的抽象类中声明静态方法吗?

Dart 中 == 和 === 有什么区别?

`FutureOr` 的目的是什么?

如何在 Dart 中获取文件名?

Dart 中的 Math.round() 在哪里?

如何在 Dart 中将日期/时间字符串转换为 DateTime 对象?