我正在嘗試構建一個顫動視圖,該視圖從資料庫呼叫中加載專案串列(代碼片段中的“成本代碼”)。此代碼在我的專案中的其他地方作業,我已經在資料庫中有資料,但是當它嘗試從空節點讀取資料時失敗。我可以在第一次運行時為我的用戶提供虛擬資料或示例資料,但他們可能會在添加自己的資料之前洗掉資料,這會導致應用程式在下次加載此視圖時崩潰。
處理 StreamBuilder 中可能為空的串列的正確方法是什么?
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: dbPathRef.onValue,
builder: (context, snapshot) {
final costCodes = <CostCode>[];
if (!snapshot.hasData) {
return Center(
child: Column(
children: const [
Text(
'No Data',
style: TextStyle(
color: Colors.white,
),
)
],
),
);
} else {
final costCodeData =
// code fails on the following line with the error
// 'type "Null" is not a subtype of type "Map<Object?, dynamic>" in type cast'
(snapshot.data!).snapshot.value as Map<Object?, dynamic>;
costCodeData.forEach(
(key, value) {
final dataLast = Map<String, dynamic>.from(value);
final account = CostCode(
id: dataLast['id'],
name: dataLast['name'],
);
costCodes.add(account);
},
);
return ListView.builder(
shrinkWrap: false,
itemCount: costCodes.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(
costCodes[index].name,
style: const TextStyle(color: Colors.white),
),
subtitle: Text(
costCodes[index].id,
style: const TextStyle(color: Colors.white),
),
);
},
);
}
},
);
}
uj5u.com熱心網友回復:
就個人而言,我傾向于避免在 UI 代碼中處理來自資料庫的原始資料,并在存盤庫/塊層中處理所有這些。
但是,要解決您的問題,您只需?在演員表的末尾添加一個,如下所示:
final costCodeData = (snapshot.data!).snapshot.value as Map<Object?, dynamic>?;
您將不再獲得強制轉換例外 - 但是您仍然必須測驗 costCodeData 是否為空。
此代碼塊可能會有所幫助:
final data = snapshot.data;
final Map<Object?, dynamic>? costCodeData
if (data == null) {
costCodeData = null;
} else {
costCodeData = (snapshot.data!).snapshot.value as Map<Object?, dynamic>?;
}
if (costCodeData == null){
// Show noData
} else {
// Show data
}
uj5u.com熱心網友回復:
final dataLast = Map<String, dynamic>.from(value);
final account = CostCode(
id: dataLast['id'],
name: dataLast['name'],
);
costCodes.add(account);
},
您使用具有鍵為字串的 Map 宣告了 dataLast,但在帳戶變數中,id 和 name 不是字串格式,請將它們保留在 "" || '' 即使在修改了這些之后,如果您仍然遇到其他問題,請嘗試在行尾放置問號 (snapshot.data!).snapshot.value as Map<Object, dynamic>?
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/523015.html
標籤:扑流构建器
下一篇:type'_InternalLinkedHashMap<String,dynamic>'不是使用http包的'String'型別的子型別
