簡體   English   中英

列出空安全 Flutter

[英]List null safety Flutter

在沒有required關鍵字的情況下在顫振中使用空安全時,如何在構造函數中初始化List<Object>

我有以下代碼:

List<String> test = [];
MyConstructor({this.test});

有一個編譯錯誤告訴我添加required關鍵字,但如果我這樣做:

List<String> test = [];
MyConstructor({this.test=[]});

這給了我一個錯誤,即the default value of a named param must be constant
當然,我可以輸入required關鍵字,一切都很好,但是在我所有的構造函數中,我都需要添加一個空List這很無聊,因為只有 10% 的時間我需要傳遞一個非空List

您能否簡單地確認required關鍵字是唯一的選項?

謝謝

  • 使用const初始值設定項:

     List<String> test; MyConstructor({this.test = const []});

    但是,如果您稍后需要改變您的List (並且如果您的List成員也是final則不可能),這將是尷尬的。

  • 根據required標記參數。

  • 使參數(但不是成員)可以為空:

     List<String> test; MyConstructor({List<String>? test}) : test = test ?? [];

    另請參閱:可選參數的默認值必須是常量

  • 使成員和參數都可以為空。

您可以改用位置參數。

class MyConstructor {
  List<String> test = [];
  MyConstructor(this.test);
}

您可以使用 const 文字作為帶有可選參數的默認值。

class MyConstructor {
  List<String> test = [];
  MyConstructor({this.test = const []});
}

只需在空列表之前添加 const ,如下所示:

  List<String> test = [];
  MyConstructor({this.test = const []});

暫無
暫無

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

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