【问题标题】:Flutter & Firestore - How to create a class object from a nested map from FirestoreFlutter & Firestore - 如何从 Firestore 的嵌套映射创建类对象
【发布时间】:2021-05-25 17:27:01
【问题描述】:

我正在尝试将 firestore 文档快照映射到我创建的自定义对象,但这样做时出现此错误:

E/flutter (6555): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] 未处理的异常:类型“(动态)=> TestMap”不是类型“(字符串,动态)的子类型=> MapEntry' of 'transform'

据我了解,这与我解析嵌套地图“testMap”的方式有关。那里有任何 Flutter/Firebase/Dart 专家可以帮助我了解我做错了什么以及如何解决这个问题。

所以我在 Firestore 中的数据如下所示:

将这些数据解析为可用对象的两个类对象,如下所示:

class Categories {
  final String category;
  final String imageurl;
  List testMap = [];

  Categories(this.category, this.imageurl);
  Map<String, dynamic> toMap() => {
        "category": this.category,
        "imageurl": this.imageurl,
        "testMap": this.testMap
      };

  Categories.fromMap(Map<String, dynamic> map)
      : category = map["category"],
        imageurl = map["imageurl"],
        testMap = map["testMap"].map((map) {  // THE ERROR IS HERE (map) 
          return TestMap.fromMap(map);
        }).toList();
}

class TestMap {
  final String v1;
  final String v2;

  TestMap(this.v1, this.v2);

  Map<String, dynamic> toMap() => {
        "v1": this.v1,
        "v2": this.v2,
      };

  TestMap.fromMap(Map<dynamic, dynamic> map)
      : v1 = map["v1"],
        v2 = map["v2"];
}

最后我像这样从 Firestore 获取数据:

  fromFirestore() {

  final FirebaseAuth auth = FirebaseAuth.instance;

  Categories categoryObject;

  CollectionReference categoriesCollection =
      FirebaseFirestore.instance.collection('categories');

  categoriesCollection.doc('categories').get()
      // ignore: missing_return
      .then((docSnapshot) {
    for (var i = 1; i <= docSnapshot.data().length; i++) {
      print(docSnapshot.data()[i.toString()]['testMap'].toString());

      categoryObject = Categories.fromMap(docSnapshot.data()[i.toString()]);
    }
  });
}

我知道 firestore 映射到 Map 但错误似乎想要这种类型的子类型 '(String, dynamic)' 而不是 Map ...也许与我的类正在解析地图?

非常感谢!

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    您可能需要转换为 TestMap

     testMap = map["testMap"].map((map) {  // THE ERROR IS HERE (map) 
              return TestMap.fromMap(map);
            }).toList().cast<TestMap>;
    

    【讨论】:

      猜你喜欢
      • 2021-11-02
      • 2020-11-27
      • 2022-08-04
      • 2023-02-04
      • 2022-01-03
      • 2021-06-20
      • 2021-06-30
      • 1970-01-01
      • 2022-01-03
      相关资源
      最近更新 更多