That is, I'm trying to invoke one constructor from another, and then construct further. I can't figure out from documentation if it can be done.
Here's a contrived example, in case it helps:
class Chipmunk { Chipmunk.named(this.name); Chipmunk.famous() { this.named('Chip'); // <-- What, if anything, goes here? this.fame = 1000; } } var chip = new Chimpmunk.famous();
The keyword “this” is used to call a constructor from within another constructor in the same class. The keyword “super” is used to call the parent (super) class constructor from within child (subclass) class constructor.
You can call another constructor via the this(...) keyword (when you need to call a constructor from the same class) or the super(...) keyword (when you need to call a constructor from a superclass). However, such a call must be the first statement of your constructor.
From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation.
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://www.dartlang.org/docs/spec/latest/dart-language-specification.html#h.flm5xvbwhs6u
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With