How to call a named constructor from a generic function in Dart/Flutter

Issue

I want to be able to construct an object from inside a generic function. I tried the following:

abstract class Interface
{
  Interface.func(int x);
}
class Test implements Interface
{
  Test.func(int x){}
}
T make<T extends Interface>(int x)
{
  // the next line doesn't work
  return T.func(x);
}

However, this doesn’t work. And I get the following error message: The method 'func' isn't defined for the class 'Type'.

Note: I cannot use mirrors because I’m using dart with flutter.

Solution

Dart does not support instantiating from a generic type parameter. It doesn’t matter if you want to use a named or default constructor (T() also does not work).

There is probably a way to do that on the server, where dart:mirrors (reflection) is available (not tried myself yet), but not in Flutter or the browser.

You would need to maintain a map of types to factory functions

void main() async {
  final double abc = 1.4;
  int x = abc.toInt();
  print(int.tryParse(abc.toString().split('.')[1]));
//  int y = abc - x;
  final t = make<Test>(5);
  print(t);
}

abstract class Interface {
  Interface.func(int x);
}

class Test implements Interface {
  Test.func(int x) {}
}

/// Add factory functions for every Type and every constructor you want to make available to `make`
final factories = <Type, Function>{Test: (int x) => Test.func(x)};

T make<T extends Interface>(int x) {
  return factories[T](x);
}

Answered By – Günter Zöchbauer

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *