在 Dart 中,如何引用包含泛型参数的类型



我正在尝试获取带有泛型的类的Type。基本上我想要下面的代码:

Type myType = List<String>;

但这显然是行不通的。

我知道我可以做到以下几点:

// indirect from an instance
List<String> myList = methodCall();
Type varType = myList;
// directly without generics
Type stringType = String;

但是如何直接从泛型的定义中使其?

谢谢

Type=">

您可以使用类似

Type typeOf<T>() => T;

然后你可以写:

Type myType = typeOf<List<String>>();

如果在 VM 上运行,这可能是你要查找的内容:

void main() {
print(myType);
}
Type myType = List<String>().runtimeType;

这给了List<String>.

但是,当编译为 JS 时,同样的事情会输出JSArray<String>.

从 Dart 2.15 开始,您不再需要使用typeOf来处理类型文字 使用泛型:

var x = List;                   // Already supported
var y = typeOf<List<String>>(); // Pre-2.15 workaround
var z = List<String>;           // New in 2.15

最新更新