Home > Back-end >  Error: The argument type 'String' can't be assigned to the parameter type 'User&
Error: The argument type 'String' can't be assigned to the parameter type 'User&

Time:01-14

void main() {
 Login('John');
}

class User {
 String name;
 User(this.name);
}

class Login {
 User user;
 Login(this.user);

 print(user.name);
}

Error: The argument type 'String' can't be assigned to the parameter type 'User'.

How to fix this error or use other use case;

CodePudding user response:

Your Login constructor takes a User as first argument, not a String. You need to construct a User object and provide that to your Login constructor.

void main() {
  Login(User('John'));
}

Another issue in your code is the print(user.name); line directly in your Login class definition. That is not allowed. If you want to execute code as part of calling the constructor, you can do that like:

  Login(this.user) {
    print(user.name);
  }

So the full solution is going to look like this:

void main() {
  Login(User('John'));
}

class User {
  String name;
  User(this.name);
}

class Login {
  User user;
  Login(this.user) {
    print(user.name);
  }
}
  •  Tags:  
  • Related