I’m trying to port some Dart code to another language but I’m a little confused by the .new constructor.
Given this class:
class DynamicTreeNode {
final int id;
DynamicTreeNode(this.id);
}
and this simple main function:
void main(List<String> arguments) {
List<DynamicTreeNode> _nodes = List<DynamicTreeNode>.generate(
16,
DynamicTreeNode.new,
);
}
I can see in the debugger that each instance of DynamicTreeNode is given an incrementing id value matching the index in the List:
Can someone explain what is happening here? I thought the call to new would fail as the unnamed (and only constructor) requires an int to be passed to it.
>Solution :
If we look at the List.generate constructor we can see that the signature is
List<E>.generate(
int length,
E generator(
int index
),
{bool growable = true}
)
The generator parameter — in your case DynamicTreeNode.new — is a function that takes the position in the list it is generated into as an argument and returns the type of element of the list. So the first DynamicTreeNode in the list will be generated by DynamicTreeNode.new(0), the second one as DynamicTreeNode.new(1), etc.
