0

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.

SuperStormer
  • 4,997
  • 5
  • 25
  • 35

2 Answers2

2

Use this:

AppUser? _appUserFromFirebaseUser(User? user) {
    return user != null
        ? AppUser(
            uid: user!.uid,
            creationTime: user!.metadata.creationTime,
            email: user!.email,
            emailVerified: user!.emailVerified,
          )
        : null;
  }
}
Anas Nadeem
  • 779
  • 6
  • 10
1

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;
  }
}
croxx5f
  • 5,163
  • 2
  • 15
  • 36