如何將 null 分配給 File 變數。將 null 分配給 File 變數時出現錯誤。
File myImage=null;
(myImage==null)?
CircleAvatar(
backgroundImage:AssetImage('assets/user_new.png'),
backgroundColor: Colors.cyanAccent,
radius: 70,
)
:
CircleAvatar(
backgroundImage:FileImage(myImage),
backgroundColor: Colors.cyanAccent,
radius: 70,
)
uj5u.com熱心網友回復:
Dart 2.12 和 Flutter 2 中提供了Sound null 安全性。
使用您宣告的變數時,默認情況下不可為空,并且要使它們可以為空,您必須使用?after datatype。
例子:
int? i = null
在您的情況下,它將是
File? myImage=null;
你可以像下面這樣使用它:
(myImage==null)?
CircleAvatar(
backgroundImage:AssetImage('assets/user_new.png'),
backgroundColor: Colors.cyanAccent,
radius: 70,
)
:
CircleAvatar(
backgroundImage:FileImage(myImage!),
backgroundColor: Colors.cyanAccent,
radius: 70,
)
在這里使用時myImage您將使用!來告訴程式myImage不會為空。
注意:我們應該盡可能避免使用
!,因為它可能會導致運行時錯誤,但在您的情況下,您已經在使用三元運算子檢查空值,因此您可以安全地使用!.
uj5u.com熱心網友回復:
我想你啟用了 nullsafety。使用 nullsafety 宣告的變數沒有 a ?cannot be null。要解決您的問題,請執行以下操作。
File? myImage = null;
uj5u.com熱心網友回復:
在 Flutter中,空安全是一回事。
有了它,如果沒有?. File在您的宣告中添加一個問號,如下所示:
File? myImage = null;
在您的代碼中,如果要將其分配給引數,則需要檢查是否myImage為 null (因為現在可以為)。backgroundImage為此,您有 2 個選擇:
backgroundImage:FileImage(myImage!) //Null check: Exception throw only if null
backgroundImage:FileImage(myImage ?? _anotherWorkingFile) //If: use another standard file if null
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/426610.html
下一篇:顫振改變狀態名稱
