I’m following the documentation here to use custom objects when reading and writing cloud firestore.
Client class:
class Client {
String id;
String name;
String email;
int contactNumber;
Client({
required this.id,
required this.name,
required this.email,
required this.contactNumber,
});
factory Client.fromFirestore(
DocumentSnapshot<Map<String, dynamic>> snapshot,
SnapshotOptions? options,
) {
final data = snapshot.data();
return Client(
id: data?['id'],
name: data?['name'],
email: data?['email'],
contactNumber: data?['contactNumber'],
);
}
Map<String, dynamic> toFirestore() {
return {
"id": id,
"name": name,
"email": email,
"contactNumber": contactNumber
};
}
}
Creating collection ref along with withConverter:
CollectionReference usersCollection = FirebaseFirestore.instance
.collection('users')
.withConverter(
fromFirestore: Client.fromFirestore,
toFirestore: (Client client, options) => client.toFirestore());
But I get the following error:
The argument type ‘Map<String, dynamic> Function(Client, SetOptions?)’ can’t be assigned to the parameter type ‘Map<String, Object?> Function(Object?, SetOptions?)’.
Not sure what I’m missing here.
2
Answers
Okay turns out you don't do it for a collection but only when you're actually getting documents.
This works:
Also this for getting it as a Stream:
Try to update the DataType: