首页 > 解决方案 > 如何将类型从一个类“传递”到另一个类?

问题描述

请看下面的样本

class Foo<T> {
  Type get type => T;
}

class Bar<T> {}

void main() {
  final foo = Foo<String>();
  final Type type = foo.type;
  final bar = Bar<type>(); // <= error on [type]: 
  ///The name 'type' isn't a type so it can't be used as a type argument - line 10
}

我知道下面的基本方法,但需要提前知道Type

Bar fromFoo<T>(Foo<T> foo) => Bar<T>();

在事先不知道类型的情况下创建Bar相同类型的正确方法是什么?Foo

我在这里这里找不到我正在寻找的答案

标签: flutterdarttypes

解决方案


Francesco Iapicca通过在的构造函数中传递Foo类型来试试这个代码片段:Bar

class Foo<T> {
  Type get type => T;
}

class Bar {
  final Type t;
  Bar({this.t});
}

void main() {
  final foo = Foo<String>();
  final bar = Bar(t: foo.type);
}

注意t变量 in的类型Bartypefrom相同Foo


推荐阅读