为什么构造函数中需要 key?

tra*_*111 5 dart flutter dart-null-safety

我创建了扩展的类StatefulWidget

class RegistrationPage extends StatefulWidget {
  final String email;

  const RegistrationPage({Key key, required this.email}) : super(key: key);

  @override
  _RegistrationPage createState() => _RegistrationPage();
}
Run Code Online (Sandbox Code Playgroud)

问题是 android studio 强迫我requiredKey key. 我在谷歌上搜索了一些如何将值从屏幕传递到另一个屏幕的示例,但我从未见过有人将 required 与 Key 一起使用。我在以下时间内进行:

Navigator.push(
        context,
        new MaterialPageRoute(
          builder: (context) => RegistrationPage(email: email),
        ),
      );
Run Code Online (Sandbox Code Playgroud)

所以只是为了传递电子邮件值。我需要使 Key 可以为空才能使其工作。难道我做错了什么?

Cop*_*oad 4

因为您正在使用 null-safe Dart 并且key不能使用 null null-safe,因为它具有不可为 null 的 type Key

解决方案:

  • @traki111如果您肯定要使用“key”,请使用“required”,如果肯定不会,请删除“key”,如果您不确定,请使用“Key?”。我已经提供了所有三种可能的解决方案。 (2认同)