skip to Main Content

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


  1. You declare a variable with:

    User user;
    

    This statement tells Flutter that user will always have a value that is a valid User object. It cannot be null.

    Then later you call:

    AppState(true, null); 
    

    And that means you’re trying to assign null to user, which is not allowed (by your own code).

    You will either need to make user nullable:

    User? user;
    

    Or you will need to pass a valid User object in when you app AppState.

    Since you seem new to this, I recommend checking out the Flutter/Dart documentation on Understanding null safety and Sound null safety.

    Login or Signup to reply.
  2. 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

    class AppState {
      bool loading;
      User? user; <----------added here
      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();
      }
    
      ...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search