In Dart, can you call another constructor from a constructor

There are two possible ways to do this:

class Chipmunk {
  String name;
  int fame;

  Chipmunk.named(this.name, [this.fame]);

  Chipmunk.famous1() : this.named('Chip', 1000);
  factory Chipmunk.famous2() {
    var result = new Chipmunk.named('Chip');
    result.fame = 1000;
    return result;
  }
}

Chipmunk.famous1() is a redirective constructor. You can’t assign properties in this one, so the constructor you are calling has to allow all the properties you want to set. That’s why I added fame as an optional parameter. In this case you could make name and fame final.

Chipmunk.famous2() is a factory constructor and can just create the instance you want. In this case, fame couldn’t be final (obviously it could be if you used the fame parameter in the named constructor).

The first variant would probably be the preferable one for your use case.

This is the documentation in the language spec:

A generative constructor consists of a constructor name, a constructor parameter list, and either a redirect clause or an initializer list and an optional body.

https://dart.dev/docs/spec/latest/dart-language-specification.html#h.flm5xvbwhs6u

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)