Flutter/Dart中如何遍历自定义类型并将其作为泛型参数正确传入方法
Dart遍历自定义类型作为泛型参数的问题解决方案
问题核心原因
你的代码存在两个错误导致泛型无法正常识别:
- 泛型类型判断逻辑错误:
T is Square用于判断变量T是Square的实例,而你此处的T是类型本身,需改为T == Square判断两个类型相等。 - Dart不支持将运行时拿到的
Type类型值直接作为泛型实参传递,泛型参数要求是编译期可确定的静态类型,你遍历shapes列表拿到的Type对象无法直接传入getShape<T>的泛型位置。
解决方案
方案1:去掉泛型,直接传Type类型参数
class Square {} class Rectangle {} dynamic getShape(Type type) { if(type == Square) return Square(); if(type == Rectangle) return Rectangle(); return null; } void main() { List<Type> shapes = [Square, Rectangle]; for (var type in shapes) { final shape = getShape(type); print(shape.runtimeType); // 依次输出Square、Rectangle } }
如果要减少if判断,可通过构造函数映射表优化:
class Square {} class Rectangle {} final Map<Type, Function> shapeFactory = { Square: () => Square(), Rectangle: () => Rectangle(), }; dynamic getShape(Type type) => shapeFactory[type]?.call(); void main() { List<Type> shapes = [Square, Rectangle]; for (var type in shapes) { print(getShape(type).runtimeType); } }
方案2:保留泛型,将泛型调用包装为函数存入列表
如果你需要保留getShape的泛型特性,可以把对应类型的泛型调用逻辑包装成函数存入列表,绕开运行时传Type当泛型的限制:
class Square {} class Rectangle {} T getShape<T>() { if(T == Square) return Square() as T; if(T == Rectangle) return Rectangle() as T; throw ArgumentError('不支持的类型:$T'); } void main() { // 列表内存储对应泛型版本的调用函数 List<Function> shapeGetters = [ () => getShape<Square>(), () => getShape<Rectangle>(), ]; for (var getter in shapeGetters) { final shape = getter(); print(shape.runtimeType); } }
内容的提问来源于stack exchange,提问作者raphire
相关产品推荐
相关产品推荐

