dictionary - 如何将从cloud_firestore接收的数据转换为Map

标签 dictionary flutter dart google-cloud-firestore cloud

cloud_firestore数据库中的数据为JSON形式。但是,如何从Map列表中的JSON转换数据?
The dummy data in my firestore

最佳答案

数据到 map 列表:

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)转换为食物 list :
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);

关于dictionary - 如何将从cloud_firestore接收的数据转换为Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59042915/

相关文章:

ios - 在 Swift 中使用协议(protocol)作为类型时出错

javascript - 从 Map.values() 选择一个属性

java - 比较映射和列表时如何将 Java 7 重构为 Java 8

Flutter list.builder 不滚动

flutter - 有没有更好的方法来将数据传递给没有状态的,继承的小部件的子级?

asynchronous - 未处理的异常Future dynamic不是FutureOr List Books类型的子类型

c# - 哪种向 ASP.NET Dictionary 类添加项目的方法效率更高?

Flutter - 如何在不每次都下载 flutter & dart sdk 的情况下切换 flutter channel

angularjs - 服务器是否需要使用Polymer.dart和/或Angular.Dart运行某些CLIENT端DART应用程序?

flutter - 使用 Streambuilder 包装 CustomScrollView 和 Sliverlist 会引发异常