我希望能够从泛型函数内部构造对象.我try 了以下方法:

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

然而,这是行不通的.我得到以下错误信息:The method 'func' isn't defined for the class 'Type'.

Note:我不能用镜子,因为我用的是带有Flutter 的省道.

推荐答案

DART不支持从泛型类型参数实例化.您想使用命名构造函数还是默认构造函数都无关紧要(T()也不起作用).

可能有一种方法可以在服务器上实现这一点,其中dart:mirrors(反射)是可用的(我自己还没有try 过),但不是在Flatter或浏览器中.

您需要维护类型到工厂函数的映射

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

Flutter相关问答推荐

如何在flutter中获得类似属性的float(CSS属性)

如何防止alert 对话框在收到通知时出现在某个flutter页面中

如何从模型列表中生成DropdownButtonFormField?

创建后检索FiRestore文档ID

将目标平台设置为Flutter 构建

我的flutter代码显示一个小部件被认为是死代码,为什么?

使用Future函数的容器中未显示图像,但在使用图像小工具时显示

为什么我的PUT请求不能正常工作?

如何创建这样的按钮

使用 forLoops 在 Dart 中进行单元测试会返回 stackoverflow

如何将 Flutter 项目迁移到具有多个插件的 Gradle 8?

Flutter http 请求获取 null

如何获取flutter中gridview项目占用的高度和宽度?

Flutter屏幕适配 - 在模拟器和真实手机上文本尺寸不同

在 Flutter 中,SpinEdit 叫什么?

我可以在列表图块下方添加其他小部件吗

如何格式化网址?

Flutter 中的 Firebase 后台消息处理程序产生重复的隔离并运行应用程序两次

type '_InternalLinkedHashMap' 不是使用 http 包的'String' 类型的子类型

如何将所有行项目平等地放在一行中?Flutter