Flutter 2.0 / Dart - 如何创建带有可选参数的构造函数?

Civ*_*ner 1 constructor optional-parameters flutter flutter-navigation dart-null-safety

我创建了一个类,并希望某些参数是可选的,但不知道该怎么做。

class PageAction {
  PageState state;
  PageConfiguration page;
  List<PageConfiguration> pages;
  Widget widget;

  PageAction({
    this.state = PageState.none,
    this.page, // Optional
    this.pages, // Optional
    this.widget, // Optional
  });
Run Code Online (Sandbox Code Playgroud)

我收到添加“必需”的建议,但这不是我需要的。有人可以帮忙解释一下吗?

Mar*_*ijn 7

标题说的是 Flutter 2.0,但我假设你的意思是 dart 2.12 null-safety。在您的示例中,所有参数都是可选的,但这不会编译,因为它们不可为空。解决方案是用“?”将参数标记为可为空。

Type? variableName // ? marks the type as nullable.
Run Code Online (Sandbox Code Playgroud)
class PageAction {
  PageState? state;
  PageConfiguration? page;
  List<PageConfiguration>? pages;
  Widget? widget;

  PageAction({
    this.state = PageState.none,
    this.page, // Optional
    this.pages, // Optional
    this.widget, // Optional
  });
Run Code Online (Sandbox Code Playgroud)