如何在Flutter中使用FirestorewithConverter

我看到最近cloud_firestore: ^2.0.0更新带来了新withConverter功能。

我想用它来检索我的模型并将其传递到 Firestore,但我不太确定如何使用现有代码执行此操作。

例如,如何更新以下代码以使用我的自定义模型?

FirebaseFirestore.instance.collection('movies').add({
  'length': 123,
  'rating': 9.7,
});

回答

Firestore 类型

首先,从 开始,现在输入2.0.0所有 Firestore引用查询。这意味着, ,现在都有一个泛型类型参数CollectionReference<T>DocumentReference<T>Query<T> T

默认

默认情况下(例如调用时FirebaseFirestore.instance.collection()),这个泛型是Map<String, dynamic>. 这意味着(不调用withConverter),您传递的数据和您接收的数据始终是 类型Map<String, dynamic>

withConverter

现在,您可以withConverter在各个地方使用以更改此类型:

  • DocumentReference.withConverter
final modelRef = FirebaseFirestore.instance
    .collection('models')
    .doc('123')
    .withConverter<Model>(
      fromFirestore: (snapshot, _) => Model.fromJson(snapshot.data()!),
      toFirestore: (model, _) => model.toJson(),
    );
  • CollectionReference.withConverter
final modelsRef =
    FirebaseFirestore.instance.collection('models').withConverter<Model>(
          fromFirestore: (snapshot, _) => Model.fromJson(snapshot.data()!),
          toFirestore: (model, _) => model.toJson(),
        );
  • Query.withConverter
final personsRef = FirebaseFirestore.instance
    .collection('persons')
    .where('age', isGreaterThan: 0)
    .withConverter<Person>(
      fromFirestore: (snapshot, _) => Person.fromJson(snapshot.data()!),
      toFirestore: (model, _) => model.toJson(),
    );

调用时会发生什么withConverter泛型类型T设置为您的自定义Model(例如Person在最后一个示例中)。这意味着对文档引用、集合引用或查询的每个后续调用都将使用该类型而不是 Map<String, dynamic>.

用法

该方法的用法很简单:

  • 您传递一个FromFirestore将快照(带选项)转换为自定义模型的函数。
  • 您传递了一个ToFirestore转换模型的函数T(带选项)回一个Map<String, dynamic>,即特定于Firestore 的 JSON 数据。

例子

这是withConverter与自定义Movie模型类一起使用的示例(请注意,我使用的freezed是因为它更具可读性):

Future<void> main() async {
  // Create an instance of our model.
  const movie = Movie(length: 123, rating: 9.7);

  // Create an instance of a collection withConverter.
  final collection =
      FirebaseFirestore.instance.collection('movies').withConverter(
            fromFirestore: (snapshot, _) => Movie.fromJson(snapshot.data()!),
            toFirestore: (movie, _) => movie.toJson(),
          );
  
  // Directly add our model to the collection.
  collection.add(movie);
  // Also works for subsequent calls.
  collection.doc('123').set(movie);

  // And also works for reads.
  final Movie movie2 = (await collection.doc('2').get()).data()!;
}

@freezed
class Movie with _$Movie {
  const factory Movie({
    required int length,
    required double rating,
  }) = _Movie;

  factory Movie.fromJson(Map<String, dynamic> json) => _$MovieFromJson(json);
}


以上是如何在Flutter中使用FirestorewithConverter的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>