简体   繁体   中英

The getter 'documents' isn't defined for the type 'QuerySnapshot<Map<String, dynamic>>'

The type 'List<QueryDocumentSnapshot<Map<String, dynamic>>>' used in the 'for' loop must implement 'Iterable' with a type argument that can be assigned to 'Map<dynamic, dynamic>'.dart(for_in_of_invalid_element_type) Changed from this code:

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;
   });
   }

To this, but getting an error. Where did I go wrong?

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;
  });
  }

The elements of result.docs are QueryDocumentSnapshot , and not a Map .

I think you're looking for:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM