【问题标题】: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;
  });
  }

【问题讨论】:

    标签: android firebase flutter dart mobile-application


    【解决方案1】:

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

    我想你正在寻找:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-18
      • 2021-12-30
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 2021-11-15
      • 2020-12-21
      • 2021-04-18
      相关资源
      最近更新 更多