'Why am I getting a type mismatch error in this code?

The Firebase UserCredential interface has a field called user that is of type User. I have a method that accepts a parameter of type User, but when I call the method, I get the following error:

The argument type 'User?' can't be assigned to the parameter type 'User'.

I am fetching my UserCredential by awaiting signInAnonymously() which returns a Promise<UserCredential>, so I'm not sure how userCredential.user is being typed as User?.

Here is my code:

loginAno() async {
    UserCredential userCredential =
        await FirebaseAuth.instance.signInAnonymously();
    onSignInAno(userCredential.user); // Problem Is Here 
}

Why am I getting this error? userCredential.user is a User, not a User?.



Solution 1:[1]

The userCredential.user field may be null, so it is declared as User?.

Since your onSignInAno expects a User, you should only call it when userCredential.user is not null. So:

loginAno() async {
    UserCredential userCredential =
        await FirebaseAuth.instance.signInAnonymously();
    if (userCredential.user !== null) {
        onSignInAno(userCredential.user);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frank van Puffelen