Flutter Firebase Firestore withConverter() method provides Map<String, dynamic> data to convert to object and from object Map<String, dynamic>.
So with this we convert Map to object and object to Map.
Because Firebase Firestore default way storing and retrieving data is Map<String, dynamic>. This is not very efficient and error prone.
Look at the example below how to use withConverter()
var usersbase = await db.collection("users").withConverter(
fromFirestore: UserData.fromFirestore,
toFirestore: (UserData userdata, options) => userdata.toFirestore(),
).where("id", isEqualTo: id).get();
withConverter has fromFirestore and toFirestore properties.
fromFirestore takes the Map data and converts to object. toFirestore does the opposite.
We also do query using where() function. Here we do id query. You can do any kind of query you want.
Now it means, if you work with withConverter() method you have to have a model class for converting data to object and to json or Map.
Below is the example of my UserData model. Your model could be anything.
class UserData {
final String? id;
final String? name;
final String? email;
final String? photourl;
final String? location;
final String? fcmtoken;
final Timestamp? addtime;
UserData({
this.id,
this.name,
this.email,
this.photourl,
this.location,
this.fcmtoken,
this.addtime,
});
factory UserData.fromFirestore(
DocumentSnapshot<Map<String, dynamic>> snapshot,
SnapshotOptions? options,
) {
final data = snapshot.data();
return UserData(
id: data?['id'],
name: data?['name'],
email: data?['email'],
photourl: data?['photourl'],
location: data?['location'],
fcmtoken: data?['fcmtoken'],
addtime: data?['addtime'],
);
}
Map<String, dynamic> toFirestore() {
return {
if (id != null) "id": id,
if (name != null) "name": name,
if (email != null) "email": email,
if (photourl != null) "photourl": photourl,
if (location != null) "location": location,
if (fcmtoken != null) "fcmtoken": fcmtoken,
if (addtime != null) "addtime": addtime,
};
}
}