简体   繁体   中英

Can I use generics in Dart like this?

I want to parse http response to Dart object,so I defined a abstract class

BaseBean:

 abstract class BaseBean{ BaseBean.fromJson(Map<String, dynamic> json); Map<String, dynamic> toJson(); } 

And I used it in a function:

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

but T.fromJson() has an error:

The method 'fromJson' isn't defined for the class 'Type'

So,can I use generics in Dart like this?Is there a better way to solve this problem?

Yes, of course, it is possible, but only with a workaround:

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\'');
  }
}
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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM