我在遷移到Flutter 的 null-safety時遇到問題,我知道在工廠中它不應該再return null這樣 Ireturn throw ArgumentError("")了,但是在我的服務中,我將canvas的值設為null,這就是它發送錯誤的地方,但是什么我想要的是繼續應用程式并將該值保留為null。
為了更好地解釋它;我有兩個模型,ModelA有一個名為ModelBcanva型別的變數。當我向ModelA發送資料映射時,變數從服務器到達null,因此它輸入一個條件并給出錯誤。canva
型號A:
class ModelA extends A {
ModelA ({
required ModelB? background,
required ModelB? canvas,
}) : super(
background,
canvas,
);
factory ModelA.fromMap(Map<String, dynamic>? map) {
if (map == null) throw ArgumentError('ModelA map must not be null');
return ModelA(
background: ModelB.fromMap(map['background']), // go in with not-null service value
canvas: ModelB.fromMap(map['canvas']), // go in with null service value
);
}
}
型號B:
class ModelB extends B {
ModelB({
String? content,
}) : super(
content;
);
factory ModelB.fromMap(Map<String, dynamic>? map) {
// * before the migration null-safety
// if (map == null) return null
if (map == null) throw ArgumentError('ModelB map must not be null'); // enter here (error)
return ModelB(
content: map['content'],
);
}
}
錯誤發生后,我進入我的應用程式沒有任何問題,但它不再運行我的功能......
這是我進行編程以保存并回傳我的完整ModelA的地方。
final someList = List<ModelA>.from(
listFromServer.where((i) {
return (i['someType'] == 1));
}).map(
(i) {
print("enter here");
final isBackOrCan = i['background'] ?? i['canvas'];
if (isBackOrCan != null) {
newListModelB
.add(ModelB.fromMap(isBackOrCan));
}
return ModelA.fromMap(i); // enter here the map background not null and also the canva null
},
),
);
[ ... more code that i want to continue ...]
} catch (e) {
print(e); // the message
throw CacheException();
}
錯誤 :

uj5u.com熱心網友回復:
如果要保留 return 的舊行為null,只需使用static方法而不是factory建構式。(無論如何factory,建構式幾乎沒有為static方法提供任何優勢。)這將是最簡單和最直接的解決方法。
但是,如果您真的想禁止null,那么首先應該要求不可為空,ModelA.fromMap然后您需要繼續呼叫鏈以使呼叫者檢查值。在你的情況下:ModelB.fromMapmapnull
class ModelA extends A {
ModelA({
required ModelB? background,
required ModelB? canvas,
}) : super(
background,
canvas,
);
factory ModelA.fromMap(Map<String, dynamic> map) {
var background = map['background'];
var canvas = map['canvas'];
return ModelA(
background: background == null
? null
: ModelB.fromMap(background), // go in with not-null service value
canvas: canvas == null
? null
: ModelB.fromMap(canvas), // go in with null service value
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/409980.html
標籤:
上一篇:如何在顫動中忽略json回應中的arrayList項?
下一篇:我不明白如何使用串列修復錯誤
