Dart Constructor Named and Positional Constructor Parameters

Question:-


 Consider the following piece of code:

class Person {
  String id;
  String name;
  ConnectionFactory connectionFactory;

  // What is this constructor doing?
  Person({this.connectionFactory: _newDBConnection});

}

If you precede a constructor's argument with this, the corresponding field will be automatically initialized, but why {...}?


Answer:-

This makes the argument a named optional argument.

When you instantiate a Person you can

Person p;
p = new Person(); // default is _newDbConnection
p = new Person(connectionFactory: aConnectionFactoryInstance);
  • without {} the argument would be mandatory
  • with [] the argument would be an optional positional argument

Comments