You need to enable JavaScript to run this app. Flutter/Firestore 如何读取Firebase中的嵌套元素并转为自定义对象
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 23:06:11