withConverter<R extends Object?> abstract method

  1. @override
CollectionReference<R> withConverter<R extends Object?>({
  1. required FromFirestore<R> fromFirestore,
  2. required ToFirestore<R> toFirestore,
})
override

Transforms a CollectionReference to manipulate a custom object instead of a Map<String, dynamic>.

This makes both read and write operations type-safe.

final modelsRef = FirebaseFirestore
    .instance
    .collection('models')
    .withConverter<Model>(
      fromFirestore: (snapshot, _) => Model.fromJson(snapshot.data()!),
      toFirestore: (model, _) => model.toJson(),
    );

Future<void> main() async {
  // Writes now take a Model as parameter instead of a Map
  await modelsRef.add(Model());

  // Reads now return a Model instead of a Map
  final Model model = await modelsRef.doc('123').get().then((s) => s.data());
}

Implementation

// `extends Object?` so that type inference defaults to `Object?` instead of `dynamic`
@override
CollectionReference<R> withConverter<R extends Object?>({
  required FromFirestore<R> fromFirestore,
  required ToFirestore<R> toFirestore,
});