我可以像这样在 Dart 中使用泛型吗?

缘去皆*_*去皆空 7 dart flutter

我想解析对 Dart 对象的 http 响应?所以我定义了一个抽象类

基豆?

abstract class BaseBean{

  BaseBean.fromJson(Map<String, dynamic> json);

  Map<String, dynamic> toJson();

}
Run Code Online (Sandbox Code Playgroud)

我在函数中使用了它?

Future<ResultData<T>> netFetch<T extends BaseBean>(){
  ......
  return new ResultData(T.fromJson(), result, code);
}
Run Code Online (Sandbox Code Playgroud)

T.fromJson()有一个错误:

未为类“Type”定义方法“fromJson”

那么,我可以像这样在 Dart 中使用泛型吗?有没有更好的方法来解决这个问题?

mez*_*oni 0

是的,当然这是可能的,但只有一个解决方法:

T unmarshal<T>(Map map, {Type type}) {
  if (type == null) {
    type = T;    
  }

  switch (type) {
    case Order:
      return Order.fromJson(map) as T;
    case OrderItem:
      return OrderItem.fromJson(map) as T;
    case Product:
      return Product.fromJson(map) as T;
    default:
      throw StateError('Unable to unmarshal value of type \'$type\'');
  }
}
Run Code Online (Sandbox Code Playgroud)
var order = unmarshal<Order>(data);
//
var product = unmarshal(data, type: Product) as Product;
//
var type = <String, Type>{};
types['OrderItem'] = OrderItem;
// ...
var type = types['OrderItem'];
var orderItem = unmarshal(data, type: type);
Run Code Online (Sandbox Code Playgroud)

  • 有一个更好的方法吗? (8认同)