I have a Stream from Firestore that I can write to. However when I try to read documents in a collection, if there is a null value I get no results (in the UI). When I create GuestBookMessage objects with empty strings I get X results which corresponds to the number of documents in the database.
When there are no null properties in Firestore I get the correct results.
Is there something I can do to ensure null-safety from firestore document properties in Dart?
FirebaseAuth.instance.userChanges().listen((user) {
if (user != null) {
_loggedIn = true;
_guestBookSubscription = FirebaseFirestore.instance
.collection('guestbook')
.orderBy('timestamp', descending: true)
.snapshots()
.listen((snapshot) {
_guestBookMessages = [];
for (final document in snapshot.docs) {
String name = document.data()['name'] as String ?? 'Default Name';
String message = document.data()['text'] as String;
_guestBookMessages.add(
GuestBookMessage(
name: name,
message: message,
),
);
}
notifyListeners();
});
} else {
...
}
...
});
Here’s a screenshot of my database from Firestore.
I come from Swift and have little experience with Firebase if that helps.
3
Answers
The solution was to assign the property value from Firestore to an optional string and not just a string.
String? name = document.data()['name'] as String? ?? 'default name';
(String? and not String)
Thanks everyone for your input.
To handle null properties in Firestore documents in Dart, you can use null-aware operators like ?? and ?. to provide default values or handle null values gracefully.
For example:
Here, an empty string (”) is assigned as the default value instead of "Default Name". This ensures consistency and avoids unexpected behavior if your name field should ever be an empty string in Firestore.
Another way to handle null values is with the ternary operator:
This expression checks if document.data()[‘name’] is not null. If true, it assigns the value as a string. Otherwise, it assigns an empty string.
If you know a field might often be empty, consider setting a default value in Firestore itself. This simplifies your code in Flutter and avoids null checks altogether. You can set default values in the Firestore console or by setting them during document creation.
For a more robust approach, you can define your GuestBookMessage class with optional fields using Dart’s null safety features:
Here, name is marked as nullable (?), allowing it to be null. When creating the object, you can check for null values and handle them appropriately.