Don't explicitly initialize variables to null

Viewed 2708

I am trying to figure out how to pass a null argument in the constructor, but I am getting this error:

Don't explicitly initialize variables to null

class Dog {
  final id int;
  final String name;
  final int age;

  Dog({this.id=null, this.name, this.age});
}

I don't want to pass an id to the constructor. I want to call the constructor like this:

  var dog = Dog(
    name: 'Rex',
    age: 15,
  );

How do I accomplish this?

2 Answers

By not explicitly assigning to null

class Dog {
  final id int;
  final String name;
  final int age;

  Dog({this.id, this.name, this.age});
}

Remember, be default value of id is set to null. So if the consumer doesn't pass a value for id it will continue to have null and so will name

If you want to make any parameter mandatory then you should mark that with @required

If you don't set variable the default value will be null.

Related