Home > Mobile >  I am learning flutter from a book that seems outdated. What is the modern way of implementing this c
I am learning flutter from a book that seems outdated. What is the modern way of implementing this c

Time:12-22

//VS code reads the error: The function can't be unconditionally invoked because it can be 'null'.

Future<void> sendEmailVerification() async {
    User user = await _firebaseAuth.currentUser();
    user.sendEmailVerification();
  }

`

adding a null check

Future<String> currentUserUid() async {
    User user = await _firebaseAuth.currentUser!();
    return user.uid;
  }

CodePudding user response:

Flutter is telling you there might be null values.

Check what's the return of currentUser() method, it might be User? (this value can be null). If so, you should code it like this:

Future<String> currentUserUid() async {
  User? user = await _firebaseAuth.currentUser(); // if the return is a null value user will be null
  return user!.uid;
}

Here you should think what you want to return if your user is null, or ignore and run into an error if null with the '!'.

If you want to control the null case:

Future<String> currentUserUid() async {
  User? user = await _firebaseAuth.currentUser(); // if the return is a null value user will be null
  return user.uid ?? 'No user right now';
}

'??' returns the right part when the first is null.

And I guess you're right and the book is outdated since the null safety is relatively new in Flutter (march 2021)

  • Related