I am new to firebase and am trying to use firebase authenticator. Currently I have 2 dart files - main.dart and user.dart.
In user.dart below, I am facing this issue with null safety.
On the last line, I am facing the error: A value of type 'Null' can't be assigned to a parameter of type 'User' in a const constructor.
So to resolve this, I decided to change line 7 to final User? data;
which resolved the issue. However, the problem now arises in my main.dart file.
Here is a snapshot of my main.dart
On line 25, I receive the error: The argument type 'User?' can't be assigned to the parameter type 'User'.
So to fix this, I decided to change line 25 to (user) => CurrentUser.create(user!),
. Adding the '!'
When I run my code now, I receive this exception:
══╡ EXCEPTION CAUGHT BY PROVIDER ╞══════════════════════════════════════════════════════════════════
The following assertion was thrown:
An exception was throw by _MapStream<User?, CurrentUser> listened by
StreamProvider<CurrentUser>, but no `catchError` was provided.
Exception:
Null check operator used on a null value
════════════════════════════════════════════════════════════════════════════════════════════════════
Can someone please explain what is going on and how I can solve this. Thanks!
CodePudding user response:
Once you set the field data
in the class CurrentUser
as nullable, of type User?
, you also have to change the line 12 of your class, by setting the parameter received by the factory method create()
as User?
.
Like this:
factory CurrentUser.create(User? data){
return CurrentUser._(data, false);
}
CodePudding user response:
You're getting these compile-time errors since you're trying to explicitly set a NON-NULLABLE variable to null
, directly in a constructor.
Another thing that's worth mentioning is the use of the !
operator in your case. When you use the !
operator you're telling Dart that you, as the developer, are taking responsibility in making sure that the variable is not null
. Therefore, since the variable you're passing is indeed null
, a run-time error is thrown.
All of your implementation can be drastically simplified once you understand null safety. For example the isInitialValue
parameter can be easily get rid of.
Take a good read at Dart's Sound Null Safety documentation to understand so.
CodePudding user response:
make your variable is nullable or add ! to your user variable to check null