Flutter/Firestore 如何读取Firebase中的嵌套元素并转为自定义对象
问题原因
- 你代码中直接对
doc['mots']取字段的写法错误,Firebase返回的mots字段是List<dynamic>类型(每个元素是对应CarnetWords属性的Map对象),不是单个Map结构。 - 你需要先把
mots数组的所有元素逐个转换成CarnetWords实例,再整合成列表传给wordId参数。
正确实现代码
final _fireStore3 = FirebaseFirestore.instance .collection('familyAccounts') .doc(id) .collection('users') .doc('user2') .collection('vocList'); await _fireStore3.get().then((QuerySnapshot querySnapshot) { querySnapshot.docs.forEach((doc) { // 先获取mots数组,转换为List类型 List motsList = doc.get('mots') as List; // 遍历数组生成CarnetWords列表 List<CarnetWords> carnetWordsList = motsList.map((motsItem) { return CarnetWords( iD: motsItem['id'], wrong: motsItem['wrong'], right: motsItem['right'], mastery: motsItem['mastery']?.toDouble(), ); }).toList(); _carnetVoc2.add( VocList( ref: doc['ref'], titre: doc['titre'], creation: doc['dateCreation'].toDate(), modification: doc['dateModification'].toDate(), firstSession: doc['firstSession'].toDate(), latestSession: doc['latestSession'].toDate(), mastery: doc['mastery'].toDouble(), wordId: carnetWordsList, ), ); }); });
额外注意事项
- 如果你的Firestore字段可能为空,建议对所有取值逻辑增加空判断,避免空异常。
- 这里用
doc.get('mots')比直接doc['mots']的写法容错性更高,避免字段不存在时直接抛出异常。
内容的提问来源于stack exchange,提问作者SylvainJack
相关产品推荐
相关产品推荐

