我知道這個問題已被問過多次,但即使有其他帖子中的建議,我也無法解決……我有一個類Score,我想使用 Flutter 從 Firebase 后端加載。下面是這個Score類的樣子:
class Score {
final String name;
final List<String> tags;
Score(this.name, this.tags);
Score.fromJson(Map<String, dynamic> json)
: name = json['name'] ?? '',
tags = json['tags'] ?? [''];
}
現在我使用Streambuilder<QuerySnapshot>, 代碼片段從 Firebase 加載它:
List<Score> scores = snapshot.data!.docs
.map((e) => Score.fromJson(e.data()))
.toList();
這導致錯誤The argument type 'Object?' can't be assigned to the parameter type 'Map<String, dynamic>'。如果我嘗試e.data() as Map<String, dynamic>按照其他帖子中的建議進行轉換,整個應用程式會在啟動時崩潰。
有人可以幫助我如何將快照資料轉換為List<Score>? 謝謝!
uj5u.com熱心網友回復:
如果您知道要從資料庫獲取地圖,則可以使用以下命令將其Object轉換為Map:
Score.fromJson(e.data() as Map<String, dynamic>)
要將標簽轉換為 aList<String>需要不同型別的轉換:
List<String>.from(json['tags'])
要了解有關為什么這是不同型別轉換的更多資訊,請參閱Dart 中 List<String>.from() 和 as List<String> 之間的區別
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/399067.html
標籤:火力基地 扑 镖 谷歌云firestore
