簡體   English   中英

Flutter 2.0 / Dart - 如何創建帶有可選參數的構造函數?

[英]Flutter 2.0 / Dart - How to create a constructor with optional parameters?

我創建了一個 class 並希望某些參數是可選的,但不知道該怎么做。

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

我收到添加“必需”的建議,但這不是我需要的。 有人可以幫忙解釋一下嗎?

標題說 Flutter 2.0 但我假設您的意思是 dart 2.12 零安全。 在您的示例中,所有參數都是可選的,但這不會編譯,因為它們不可為空。 解決方案是使用“?”將您的參數標記為可為空。

Type? variableName // ? marks the type as nullable.
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
  });

我已經分享了關於構造函數的詳細信息,請參考我的回答https://stackoverflow.com/a/69081615/563735

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM