【问题标题】:Firestore update from 1.0 to 2.0 breaks database modelFirestore 从 1.0 更新到 2.0 破坏了数据库模型
【发布时间】:2021-07-13 20:18:58
【问题描述】:

我已经发布了我的数据库模型,然后是下面调用地图的代码。以下行>>> MarkerCollectModel model = MarkerCollectModel.fromMap(map()!) 给我一个错误错误:参数类型“Object”不能分配给参数类型“Map”。我一直在阅读迁移更改here,但似乎可以理解它们。

如何使模型与新版本的 firestore 一起工作?

class MarkerCollectModel {
  double? lat, lng;
  String? name, detail,  dateTime, uid;

  MarkerCollectModel(
      {this.lat,
        this.lng,
        this.name,
        this.detail,
        this.dateTime,
        this.uid});

  MarkerCollectModel.fromMap(Map<String, dynamic> map) {
    lat = map['Lat'];
    lng = map['Lng'];
    name = map['Speed'];
    detail = map['Racer'];
    dateTime = map['DateTime'];
    uid = map['Uid'];
  }
}



Future<void> readDataFromFirebase() async {
    print('###############readDataFromFirebase Work####################');
    Firebase.initializeApp();
    FirebaseFirestore firestore = FirebaseFirestore.instance;
    CollectionReference collectionReference =
    firestore.collection('usertest');
    collectionReference.snapshots().listen((event) {
      List<DocumentSnapshot> snapshots = event.docs;
      for (var map in snapshots) {
        MarkerCollectModel model = MarkerCollectModel.fromMap(map()!);
        String nameDocument = map.id;
        listDocuments.add(nameDocument);
        print('Name ==>> ${model.name}');
        Marker marker = createMarker(model, nameDocument);
        setState(() {
          list.add(marker);
          print('myMarkers set lenght ==>> ${myMarkers().length}');
        });
      }
    });
  }

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    根据this,您应该这样做:

    Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
    

    所以,你的情况是:

    for (var map in snapshots) {
        Map<String, dynamic> data = map!.data() as Map<String, dynamic>; // add this line
        MarkerCollectModel model = MarkerCollectModel.fromMap(data); // use data here
        String nameDocument = map.id;
        listDocuments.add(nameDocument);
        print('Name ==>> ${model.name}');
        Marker marker = createMarker(model, nameDocument);
        setState(() {
           list.add(marker);
           print('myMarkers set lenght ==>> ${myMarkers().length}');
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-13
      • 1970-01-01
      • 2014-05-16
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      • 2013-09-05
      相关资源
      最近更新 更多