I’m making flutter project, but I search in google everywhere.
Error message:
The argument type ‘Null’ can’t be assigned to the parameter type ‘User’.
I want to make app go login page if user is null, But I don’t know why User class can’t be null.
This is my code:
class AppState {
bool loading;
User user;
AppState(this.loading, this.user);
}
...
class _HomeWidgetState extends State<HomeWidget> {
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = GoogleSignIn();
int i = 0;
final app = AppState(true, null); // Error line
@override
Widget build(BuildContext context) {
if (app.loading)
return _loading();
if (app.user == null)
return _loginPage();
return _main();
}
...
}
searched official documentation about User class in dart and googled my error message
2
Answers
You declare a variable with:
This statement tells Flutter that
user
will always have a value that is a validUser
object. It cannot be null.Then later you call:
And that means you’re trying to assign
null
touser
, which is not allowed (by your own code).You will either need to make
user
nullable:Or you will need to pass a valid
User
object in when you appAppState
.Since you seem new to this, I recommend checking out the Flutter/Dart documentation on Understanding null safety and Sound null safety.
Because in dart you cannot assing a null value on a var type if you don’t declare it.
If you want to have the possibility to assign a null value to user, just declare it like
User? user
, but you have to check if it’s null in most cases you’ll use user.So, just add a ? at User, like this