Search code examples
pythondarttypesanonymous-functionanonymous-class

How to create a list of objects of certain class type in Dart?


I have this code in Python 3.x:

_VectorOf = lambda ownerObj,classType,scope: [classType(ownerObj) for i in scope]

This code create a list of "classType" objects."classType" is any class passed by user.

How would it be in Dart 2.7.x? I don't wish to use "dart:mirrors" if it is possible.

Thanks in advance.


Solution

  • List<T> vectorOf<T>(int length, T createObject()) => 
        [for (var i = 0; i < length; i++) createObject()];
    

    If you want to create an object, you have to say how to create it.

    The type is not enough. It might be enough with dart:mirrors, but only if the type actually has a constructor. And it's a class type at all, and not, say, a function type or FutureOr<void> or something else which cannot have a constructor at all.

    An example could be:

    var listOfStringLists = vectorOf(12, () => <String>[]);
    

    This creates a list of length 12 where each element is a new empty list of strings.

    If you need to parameterize the factory function with an extra parameter, then you just have to pass it through manually:

    List<T> vectorOf<T, O>(int length, O owner, T createObject(O owner)) => 
        [for (var i = 0; i < length; i++) createObject(owner)];
    

    This will pass the owner object as a parameter to factory every time it's called. Another option is:

    List<T> vectorOf<T, O>(int length, O owner, T createObject(O owner)) =>
        List<T>.generate(length, (_) => createObject(owner));
    

    where you use the List.generate constructor, but ignores the index it passes to its factory function.