![](/img/trans.png)
[英]Flutter ,dart,The parameter 'colour' can't have a value of 'null' because of its type, but the implicit default value is 'null'
[英]The parameter can't have a value of 'null' because of its type in Dart
我有以下 Dart function,我現在正在使用 null 安全:
void calculate({int factor}) {
// ...
}
分析器抱怨說:
由於其類型,參數“factor”不能具有“null”值,並且未提供非空默認值。
我的StatelessWidget
在Flutter也是這樣:
class Foo extends StatelessWidget {
const Foo({Key key}): super(key: key);
// ...
}
我收到以下錯誤:
由於其類型,參數“key”不能具有“null”值,並且未提供非空默認值。
我該如何解決這個問題?
發生這種情況的原因是因為啟用了 null 安全,您的不可空參數factor
或key
不能是null
。
在 function 和構造函數中,當調用 function 時沒有命名參數: calculate()
或Foo()
,這些值可能是null
。 但是,因為類型( int
和Key
)是不可空的,所以這是無效代碼——它們絕不能是 null。
基本上有三種方法可以解決這個問題:
required
這可能是該問題最常見的解決方案,它表明必須設置一個變量。 這意味着如果我們有(注意required
的關鍵字):
void calculate({required int factor}) {
// ...
}
我們指出必須始終指定factor
參數,這解決了問題,因為只有calculate(factor: 42)
等。 將是 function 的有效呼叫。
另一種解決方案是提供默認值。 如果我們的參數有默認值,我們可以安全地在調用 function 時不指定參數,因為將使用默認值:
void calculate({int factor = 42}) {
// ...
}
現在, calculate()
調用將使用42
作為factor
,這顯然是非空的。
第三個解決方案是您真正要考慮的問題,即您是否想要一個可為空的參數? 如果是這樣,您將不得不 null 在您的 function 中使用它時檢查該參數。
但是,這是您最常希望解決Key key
問題的方法,因為您並不總是希望在 Flutter 中為您的小部件提供一個鍵(注意可為空的Key?
類型):
class Foo extends StatelessWidget {
const Foo({Key? key}): super(key: key);
// ...
}
現在,您可以安全地構造Foo()
而無需提供密鑰。
請注意,這同樣適用於位置參數,即它們可以為 nullable 或 non-nullable,但是,它們不能用required
注釋並且不能具有默認值,因為它們始終需要傳遞。
void foo(int param1) {} // bar(null) is invalid.
void bar(int? param1) {} // bar(null) is valid.
這是將不可空特性添加到 Dart 的主要原因。因為,您將Key
傳遞給超級 class,它可能是null
,所以您要確保它不是 null。您可以做的就是不使用key
完全或為其提供默認值或使其成為required
的。 像:
MyPage({Key key = const Key("any_key")}) : super(key: key);
或像這樣要求key
:
MyPage({required Key key}) : super(key: key);
如果我從 class 指向key
的constructor
中得到這個錯誤,我會添加一個 ' ?
' 像這樣標記Key
的前面:
const ClassName({Key? key}) : super(key: key);
' ?
' 表示可以為nullable
作為對先前@creativecreatorormaybenot的回答的附加信息,您還可以使用位置參數(無大括號),默認情況下這些參數是強制性的,因此不可為空。
void calculate(int factor) {
// ...
}
並且在不命名參數的情況下被調用:
calculate(12);
這些類型的參數可以通過這種方式用於構造函數:
class Foo extends StatelessWidget {
final String myVar;
const Foo(this.myVar, {Key? key}): super(key: key);
// ...
}
和“可以后跟命名參數或可選位置參數(但不是兩者)” ,請參閱此處的文檔: dart parameters
關於命名參數和位置參數之間差異的有趣答案: What is the difference between named and positional parameters in Dart?
為例如添加所需的 function
required Key key,
required this.id,
required this.name,
required this.code,
required this.img,
required this.price,
required this.promotionPrice,
required this.size,
required this.color,
在 pubspec 中更改 sdk 版本
environment:
sdk: ">=2.7.0 <3.0.0"
在構造函數中的變量前添加一個 required 關鍵字,並添加 '?' 鑰匙旁邊。
MyHomePage({Key? key, required this.title}) : super(key: key);
更改 pubspec.yaml 中的 SDK 版本可解決以下問題:
環境:sdk:“>=2.1.0 <3.0.0”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.