Search code examples
flutterdartdart-null-safety

Upgrading Firebase User model to null safety


I've finally taken the plunge to upgrade my app to Null Safety, but am having problems upgrading the following code.

(If not obvious, I'm mapping the Firebase User model to a local AppUser model, and using this as authentication wrapper around the entire app.)

class AuthService with ChangeNotifier {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  late AuthResultStatus _authStatus;

  Stream<AppUser> get appUser {
    return _auth.userChanges().map(_appUserFromFirebaseUser);
  }

AppUser _appUserFromFirebaseUser(User user) {
    return user != null
        ? AppUser(
            uid: user.uid,
            creationTime: user.metadata.creationTime,
            email: user.email,
            emailVerified: user.emailVerified,
          )
        : null;
  }
}


class AppUser {
  final String? uid;
  final DateTime? creationTime;
  final String? email;
  final bool? emailVerified;

  AppUser({
    this.uid,
    this.creationTime,
    this.email,
    this.emailVerified,
  });
}

How do I return either a local AppUser model or null? Appreciate your pointers.


Solution

  • You said it yourself, you want to have an AppUser or null, thats just AppUser?. Just make this change in the method and in the stream.

    class AuthService with ChangeNotifier {
      final FirebaseAuth _auth = FirebaseAuth.instance;
      late AuthResultStatus _authStatus;
    
      Stream<AppUser?> get appUser {
        return _auth.userChanges().map(_appUserFromFirebaseUser);
      }
    
    AppUser? _appUserFromFirebaseUser(User user) {
        return user != null
            ? AppUser(
                uid: user.uid,
                creationTime: user.metadata.creationTime,
                email: user.email,
                emailVerified: user.emailVerified,
              )
            : null;
      }
    }