简体   繁体   English

Dart/Flutter - 调用未知混凝土 class 的构造函数(从 Type 获取 class)

[英]Dart/Flutter - Call constructor of unknown concrete class (get class from Type)

I want to call the constructor of a concrete class, but I only have a Type which implements an interface.我想调用一个具体的 class 的构造函数,但我只有一个实现接口的Type Is it possible to get the concrete class from that Type and call its constructor without actually having to know it?是否可以从该Type中获取具体的 class 并调用其构造函数而无需实际知道它?

My current workaround is a switch with a cast, but that does not seem reasonable, because I have to maintain the switch whenever another class implements that interface.我当前的解决方法是使用强制转换的开关,但这似乎不合理,因为每当另一个 class 实现该接口时,我都必须维护该开关。

abstract class IFace {
  String foo();
}

class Bar implements IFace {
  String foo() => 'I am Bar';
}

T? getObject<T extends IFace>() {
  // what I'd like to do, but does not work:
  // return T();
  
  // what I have to do instead:
  switch (T) {
    case Bar:
      return Bar() as T;
    default:
      return null;
  }
}


void main() {
  Bar? bar = getObject<Bar>();
  
  print(bar?.foo()); // I am Bar
}

This is not easy thing to do just because, what if T does not have public constructor, or it has named constructor instead?这不是一件容易的事,因为如果 T 没有公共构造函数,或者它有命名构造函数怎么办? ;) ;)

I think it could be possible only with use of dart:mirrors package, which is not available on Flutter (due to AOT compilation).我认为只有使用 dart:mirrors package 才有可能,这在 Flutter 上不可用(由于 AOT 编译)。

As alternative, you can try using reflectable package, but it is not easy to do either.作为替代方案,您可以尝试使用可反射的 package,但这也不是一件容易的事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 flutter 和 dart 中的另一个 class 调用一个 class 中的方法 - Call a method in one class from another class in flutter and dart Flutter Dart | 如何从 class 构造函数返回不同的 object - Flutter Dart | How to return different object from class Constructor 如何在dart flutter中从statefulwidget类到state类获取变量? - How to get variable from statefulwidget class to state class in dart flutter? 如何从 Flutter(Dart) 中的另一个类调用方法? - How to call method from another class in Flutter(Dart)? Flutter - Dart - Reflectable 包:如何:获取类字段类型? 从类/类型实例化对象? 使用 Reflectable 设置字段值 - Flutter - Dart - Reflectable package : how to: get class fields type? instantiate object from class/Type? set fields values using Reflectable 在类之间移动变量 - Dart Flutter - Move Variable from Class to Class - Dart Flutter Flutter dart 调用超级 class 方法的超级 - Flutter dart call super of super class method 如何从 flutter 中的构造函数调用有状态 class 中的方法 - How to call method in stateful class from constructor in flutter 如何在 Dart/Flutter 的同一个 class 中获取默认构造函数和参数化构造函数? - How can I get a default and a parameterized constructor inside the same class in Dart/Flutter? Dart & Flutter:如何在另一个 class 中调用 class 方法 - Dart & Flutter: How to call for a class method inside another class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM