Chapter 6.2 Constructor specify argument type

Take this as an example:

class User {
  User({int id = 0, String name = 'anonymous'})
      : _id = id,
        _name = name;

  int _id;
  String _name;
}

I find that there is no error if I remove the argument type in the constructor:

class User {
  User({id = 0, name = 'anonymous'})
      : _id = id,
        _name = name;

  int _id;
  String _name;
}

Is there any difference between the two? When do we need to specify the argument type in the constructor?

No difference. In the second one Dart is just inferring the type from the initializing value (0 and ‘anonymous’ already have a type).

1 Like

Thank you. I think that the second is a more neat way to present the constructor.

1 Like