【问题标题】:How to transform the data received from cloud_firestore into a Map如何将从 cloud_firestore 接收到的数据转换为地图
【发布时间】:2023-04-07 13:28:01
【问题描述】:

cloud_firestore 数据库中的数据采用 JSON 格式。但是,如何在 Map 列表中转换 JSON 数据? The dummy data in my firestore

【问题讨论】:

    标签: dictionary flutter dart google-cloud-firestore cloud


    【解决方案1】:

    数据到地图列表:

    final CollectionReference ref = Firestore.instance.collection('food');
    List<Map<String, dynamic>> listOfMaps = [];
    await ref.getDocuments().then((QuerySnapshot snapshot) {
      listOfMaps =
          snapshot.documents.map((DocumentSnapshot documentSnapshot) {
        return documentSnapshot.data;
      }).toList();
    });
    print(listOfMaps);
    

    以防万一您想使用更好的方法。将数据解析为对象列表:

    1) 创建模型类:

    class Food {
      String affordability;
      String title;
    
      Food.fromJson(Map<String, dynamic> jsonData) {
        this.affordability = jsonData['affordability'];
        this.title = jsonData['title'];
      }
    }
    

    2) 转换为食物列表:

    final CollectionReference ref = Firestore.instance.collection('food');
    List<Food> list = [];
    await ref.getDocuments().then((QuerySnapshot snapshot) {
      list = snapshot.documents.map((DocumentSnapshot documentSnapshot) {
        return Food.fromJson(documentSnapshot.data);
      }).toList();
    });
    print(list);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      相关资源
      最近更新 更多