在下面的示例中,我嘗試向parsedJson['newElement']我的 Firestore 資料添加欄位檢查。問題是,如果這個欄位在被回傳的 firestore 集合映射中不存在,它會拋出一個 null 并且整個函式fromJson因為這個 null 而失敗......現在我的代碼允許從被回傳的欄位中回傳一個 null 值,并且這很好用。但是我如何安全地失敗并在可能尚不存在的欄位上分配一個空白值?我假設我在這里遺漏了一些簡單的東西。
factory ItemModel.fromJson(Map<String, dynamic> parsedJson) {
return ItemModel(
authorID: parsedJson['authorID'] ?? '',
authorName: parsedJson['authorName'] ?? '',
newElement: parsedJson['newElement'] ?? '',
);
uj5u.com熱心網友回復:
您可以像這樣使欄位為空:
class ItemModel{
String? authorID;
String? authorName;
String? newElement;
ItemModel({this.authorID, this.authorName, this.newElement});
factory ItemModel.fromJson(Map<String, dynamic> parsedJson){
return ItemModel(
authorID: parsedJson["authorID"],
authorName: parsedJson["authorName"],
newElement: parseJson["newElement"],
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/439619.html
上一篇:dartnull安全的最佳實踐
