Flutter中GridView.count读取Firebase Firestore数据报无map方法错如何解决
错误原因
- 你调用
doc(document.id).get()获取的是单个指定文档,返回结果类型为DocumentSnapshot(报错中的_JsonDocumentSnapshot是其具体实现类),不是包含多文档的QuerySnapshot,本身没有map方法 map是可迭代对象(如List、QuerySnapshot的docs属性)的专属方法,对单个文档对象调用必然触发该报错- 额外问题:
DocumentSnapshot需要调用data()方法才能获取到存储字段的Map结构,不能直接对快照对象本身取字段值
解决方案
根据你的实际需求二选一即可:
场景1:确实只需要渲染当前单文档的ProductCard
不需要调用map,直接将单文档数据转为ProductCard放入children数组即可,完整代码:
FutureBuilder( future: _firebaseServices.productsRef .doc(document.id) .get(), builder: (context, productSnap) { if (productSnap.hasError) { return Container( child: Center( child: Text("${productSnap.error}"), ), ); } if (productSnap.connectionState == ConnectionState.done) { // 先获取文档字段Map,增加判空处理避免空异常 Map<String, dynamic> documentData = (productSnap.data?.data() as Map<String, dynamic>?) ?? {}; return GridView.count( crossAxisCount: 2, shrinkWrap: true, physics: NeverScrollableScrollPhysics(), childAspectRatio: .53, mainAxisSpacing: 8.0, crossAxisSpacing: 10, padding: const EdgeInsets.only( top: 10.0, bottom: 12.0, left: 5, right: 5), // 直接把单个卡片放入数组 children: [ ProductCard( title: documentData['name'] ?? '无名称', ) ]); } return const Container( child: Center( child: CircularProgressIndicator(), ), ); });
场景2:实际需要获取多个文档渲染列表,误写为了单文档查询
将future部分改为集合查询,再通过docs属性获取文档列表调用map即可,核心修改示例:
// 1. future改为集合查询,可根据需求增加where等筛选条件 future: _firebaseServices.productsRef.get(), // 2. 单文档判断逻辑替换为如下代码 children: productSnap.data?.docs.map((document) { Map<String, dynamic> documentData = document.data() as Map<String, dynamic>; return ProductCard( title: documentData['name'] ?? '无名称', ); }).toList() ?? [],
内容的提问来源于stack exchange,提问作者FTF Studio
相关产品推荐
相关产品推荐

