如何将从cloud_firestore接收的数据转换为Map [英] How to transform the data received from cloud_firestore into a Map

查看:78
本文介绍了如何将从cloud_firestore接收的数据转换为Map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

cloud_firestore数据库中的数据为JSON形式。但是,如何从Map列表中的JSON转换数据?
我的Firestore中的虚拟数据

The data from the cloud_firestore database is in the form of JSON. However, how to transform the data from JSON in a List of Map? The dummy data in my firestore

推荐答案

数据到地图列表:

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

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

Just in case if You want to use better way. Parse data to List of Objects:

1)创建模型类:

class Food {
  String affordability;
  String title;

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

2)转换为食物列表:

2) convert to list of Food:

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

这篇关于如何将从cloud_firestore接收的数据转换为Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆