skip to Main Content

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.
firestore database

I come from Swift and have little experience with Firebase if that helps.

3

Answers


  1. Chosen as BEST ANSWER

    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.


  2. 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:

    for (final document in snapshot.docs) {
      String name = document.data()['name'] as String ?? 'Default Name'; 
      String message = document.data()['text'] as String ?? ''; // Provide an empty string if message is null
    
      _guestBookMessages.add(
        GuestBookMessage(
          name: name,
          message: message,
        ),
      );
    }
    notifyListeners();
    
    
    Login or Signup to reply.
  3. The issue you’re facing is related to how null values are handled in
    Firestore data retrieval. Here’s how to address it in your Flutter
    app:

    1. Conditional Access Operator (??):

    Your current approach with the null-check operator (??) is on the
    right track. It checks if document.data()['name'] is null and assigns
    "Default Name" if it is. However, there’s a slight improvement:

    String name = document.data()['name'] ?? '';
    

    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.

    1. Ternary Operator:

    Another way to handle null values is with the ternary operator:

    String name = document.data()['name'] != null ? document.data()['name'] as String : '';
    

    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.

    1. Consider Default Values in Firestore:

    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.

    1. Optional Fields in Dart:

    For a more robust approach, you can define your GuestBookMessage class with optional fields using Dart’s null safety features:

    class GuestBookMessage {
      final String? name;
      final String message;
    
      GuestBookMessage({this.name, required this.message});
    }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search