【问题标题】:Flutter Cloudfirestore: how to check whether field existsFlutter Cloud Firestore:如何检查字段是否存在
【发布时间】:2021-12-29 10:02:54
【问题描述】:

我的 Flutter 应用使用 Firbase Cloudfirestore 作为其后端。稍后我想向我的应用程序添加新功能,这将需要 Firestore 文档中的新字段。如何检查文档中是否存在该字段,如果不存在则返回默认值?

Stream<List<Car>> streamCars() {
    return _carsCollection.snapshots().map((snapshot) => snapshot.docs.map((document) => Car.fromDocumentSnapshot(document)).toList());
}

static Car fromDocumentSnapshot(DocumentSnapshot snapshot) {
  return Car(
    id: snapshot.id,
    date: snapshot['date'] ?? Timestamp.now(),
    seats: snapshot['seats'] ?? 0,
    newFeature: snapshot['newFeature'] ?? '', // This field does not exist yet and throws error
  );
}

这会引发错误:

Bad state: field does not exist within the DocumentSnapshotPlatform

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    你可以这样做。

    newFeature: (snapshot.data() as Map)['newFeature'] ?? ''
    

    【讨论】:

      【解决方案2】:
      static Car fromDocumentSnapshot(DocumentSnapshot snapshot) {
        return Car(
          id: snapshot.id,
          date: snapshot['date'] ?? Timestamp.now(),
          seats: snapshot['seats'] ?? 0,
          newFeature: snapshot['newFeature']==null ?'tjhjhjh': '', // check it if is null will solve the error
        );
      }
      

      【讨论】:

      • 这似乎不起作用。 a ?? b 和 a==null ? b : a 不一样吗?
      猜你喜欢
      • 2018-12-09
      • 1970-01-01
      • 2020-09-09
      • 2018-06-11
      • 2019-12-28
      • 2021-12-29
      • 2021-09-15
      • 1970-01-01
      相关资源
      最近更新 更多