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

☆樱花仙子☆ 提交于 2020-11-27 04:57:37

问题


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.


回答1:


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);
}


来源:https://stackoverflow.com/questions/55237006/how-to-call-a-named-constructor-from-a-generic-function-in-dart-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!