没有为类型 'QuerySnapshot<Map<String, dynamic>>' 定义 getter 'documents'

Posted

技术标签:

【中文标题】没有为类型 \'QuerySnapshot<Map<String, dynamic>>\' 定义 getter \'documents\'【英文标题】:The getter 'documents' isn't defined for the type 'QuerySnapshot<Map<String, dynamic>>'没有为类型 'QuerySnapshot<Map<String, dynamic>>' 定义 getter 'documents' 【发布时间】:2021-11-19 13:55:55 【问题描述】:

“for”循环中使用的类型“List>>”必须使用可分配给“Map”的类型参数实现“Iterable”。dart (for_in_of_invalid_element_type) 从此代码更改:

class CategoryServices 
String collection = "categories";
Firestore _firestore = Firestore.instance;

Future<List<CategoryModel>> getCategories() async =>
  _firestore.collection(collection).getDocuments().then((result) 
    List<CategoryModel> categories = [];
    for (DocumentSnapshot category in result.documents) 
      categories.add(CategoryModel.fromSnapshot(category));
    
    return categories;
   );
   

对此,但出现错误。我哪里做错了?

class CategoryModel 
 String? image;
  String? name;

 CategoryModel(this.image, this.name);

 // receiving data from server
 factory CategoryModel.fromMap(map) 
  return CategoryModel(image: map['image'], name: map['name']);
 

 // sending data to our server
 Map<String, dynamic> toMap() 
  return 
  'image': image,
  'name': name,
   ;
   
   

class CategoryServices 
String collection = "category";
FirebaseFirestore _firestore = FirebaseFirestore.instance;

 Future<List<CategoryModel>> getCategories() async =>
  _firestore.collection(collection).get().then((result) 
    List<CategoryModel> categories = [];
    for (Map category in result.docs)   //error at this line
      categories.add(CategoryModel.fromMap(category));
    
    return categories;
  );
  

【问题讨论】:

【参考方案1】:

result.docs 的元素是QueryDocumentSnapshot,而不是Map

我想你正在寻找:

for (QueryDocumentSnapshot category in result.docs) 
  categories.add(CategoryModel.fromMap(category.data()));

return categories;

【讨论】:

以上是关于没有为类型 'QuerySnapshot<Map<String, dynamic>>' 定义 getter 'documents'的主要内容,如果未能解决你的问题,请参考以下文章

错误:“QuerySnapshot”类没有实例获取器“数据”

Flutter/Firestore:“QuerySnapshot”类没有实例获取器“document”

Flutter Firestore QuerySnapshot 没有 getter 'document 的实例

Recyclerview 适配器:java.util.ArrayList 无法转换为 com.google.firebase.firestore.QuerySnapshot

无法在getDocuments querysnapshot(Swift)中将变量分配给Firebase数据[重复]

我是不是需要取消 Stream<QuerySnapshot> (颤振)