sivaram
sivaram

Reputation: 79

I'm getting non-nullable instance in dart how can I fix it?

here is my code

 void main() {
    user userOne=user('silver',19);
    print(userOne.name);
    superUser userTwo=superUser('sasha',1);
    print(userTwo.name);
 }

 class user{
  int age;
  String name;
  user(String name,int age){
    this.name=name;
    this.age=age;
  }
  void login(){
    print("user has logged in");
  }
}
class superUser extends user{
  superUser(String name,int age):super(name,age);
  
  void publish(){
    print("publish update");
  }
}

I'm getting these errors though I initialized the variables in the constructor.

Non-nullable instance field 'name' must be initialized.
Non-nullable instance field 'age' must be initialized.

should I initialize the integer variable to 0 and string variable to empty string?

Upvotes: 0

Views: 220

Answers (2)

Peter Haddad
Peter Haddad

Reputation: 80904

You can do:

 void main() {
    user userOne=user('silver',19);
    print(userOne.name);
    superUser userTwo=superUser('sasha',1);
    print(userTwo.name);
 }

 class user{
  int age;
  String name;
  // Syntactic sugar for setting name and age
  // before the constructor body runs.
  user(this.name, this.age);
   
  void login(){
    print("user has logged in");
  }
}
class superUser extends user{
  superUser(String name,int age):super(name,age);
  
  void publish(){
    print("publish update");
  }
}

Also it's better to use UpperCamelCase for class names, meaning User, SuperUser instead of user, superuser.

Upvotes: 1

Hazar Belge
Hazar Belge

Reputation: 1089

You can't use non-nullable properties before initalizing. So, you have 2 option:

1- Declare late variables.

class user{
  late int age;
  late String name;
  user(String name,int age){
    this.name=name;
    this.age=age;
  }
  void login(){
    print("user has logged in");
  }
}

2- Make nullable.

class user{
      int? age;
      String? name;
      user(String name,int age){
        this.name=name;
        this.age=age;
      }
      void login(){
        print("user has logged in");
      }
    }

Upvotes: 1

Related Questions