Flutter中Firestore StreamBuilder嵌套对象数据无法在ListView展示
问题原因及修复方案
- 数据源路径错误
Clothes为Closets集合下的嵌套子集合,当前代码直接读取根级clothes集合,路径不匹配无法获取数据:
- 读取单个指定Closets文档下的clothes子集合,修改stream路径:
stream: FirebaseFirestore.instance.collection("Closets").doc("对应Closets文档的ID").collection("clothes").snapshots(),- 读取所有Closets文档下的全部clothes子集合数据,使用集合组查询:
stream: FirebaseFirestore.instance.collectionGroup("clothes").snapshots(),- 数据源路径错误
- 列表项字段引用错误
Clothes实例构造时传入的名称字段为clothesName,CardClothesLemari组件内错误调用cloth.clothes取值,修改为对应字段即可:
Text( cloth.clothesName, // 替换为Clothes类中存储名称的属性名 style: TextStyle( fontSize: 14, fontFamily: GoogleFonts.openSans().fontFamily, fontWeight: FontWeight.w700, color: Color(0xffF0E8E1)), textAlign: TextAlign.center, ),- 列表项字段引用错误
- 空判断变量未定义
CardClothesLemari中已将widget.clothes赋值给cloth变量,后续空判断直接使用未定义的clothes变量,会导致判断失效或编译异常,修改为:
if (cloth == null) { return Container(); }- 空判断变量未定义
- 类型兼容适配
新版cloud_firestore库中DocumentSnapshot.data()返回类型为Object?,直接按下标读取字段可能触发类型错误,可先强转为Map类型再取值:
return new ListView( children: snapshot.data.docs .map((DocumentSnapshot doc) { Map<String, dynamic> data = doc.data() as Map<String, dynamic>; Clothes clothes = new Clothes( data['clothesId'], data['clothesName'], data['clothesDesc'], data['clothesImage'], data['clothesCloset'], data['clothesAge'], data['clothesTag'], data['clothesStatus'], data['clothesLaundry'], data['createdAt'], data['updatedAt'], ); return CardClothesLemari(clothes: clothes); }).toList(), );- 类型兼容适配
内容的提问来源于stack exchange,提问作者Michelle Alexandra
相关产品推荐
相关产品推荐

