Creating an instance of a generic type in DART

I tried mezonis approach with the Activator and it works. But it is an expensive approach as it uses mirrors, which requires you to use “mirrorsUsed” if you don’t want to have a 2-4MB js file.

This morning I had the idea to use a generic typedef as generator and thus get rid of reflection:

You define a method type like this: (Add params if necessary)

typedef S ItemCreator<S>();

or even better:

typedef ItemCreator<S> = S Function();

Then in the class that needs to create the new instances:

class PagedListData<T>{
  ...
  ItemCreator<T> creator;
  PagedListData(ItemCreator<T> this.creator) {

  }

  void performMagic() {
      T item = creator();
      ... 
  }
}

Then you can instantiate the PagedList like this:

PagedListData<UserListItem> users 
         = new PagedListData<UserListItem>(()=> new UserListItem());

You don’t lose the advantage of using generic because at declaration time you need to provide the target class anyway, so defining the creator method doesn’t hurt.

Leave a Comment