如何在flutter中将泛型类型作为参数传递给Future

时间:2019-05-23 09:04:26

标签: dart flutter

我的目标是创建一个处理Web服务器请求的单例类,并传递通用类型(这是我的数据模型)作为参数来解码并分配给我的数据模型。我下面部分完成的代码,非常感谢。

class Network{
  Future<someDataModel> _getRequest(T) async {
   print("entered");
   final response = await client
    .get("http://api.themoviedb.org/3/movie/popular?api_key=$_apiKey");
      print(response.body.toString());
   if (response.statusCode == 200) {
        // If the call to the server was successful, parse the JSON
   return T.fromJson(json.decode(response.body));
   } else {
      // If that call was not successful, throw an error.
   throw Exception('Failed to load post');
  }
 }

在同一类中,我使用下面的公共方法访问getRequest。因此,通过这种方法,我的意图是将我的数据模型作为通用类型参数传递给get请求,并让解码部分发生。如下所示,部分完成了代码。

 getAllList(){
  return _getRequest(dataModel);
 }

1 个答案:

答案 0 :(得分:1)

以下解决方案适用于通用对象以及通用对象列表(来自JSON列表响应)。

首先,您需要具有一个检查通用对象类型并返回相应fromJson调用结果的函数:

/// If T is a List, K is the subtype of the list.
static T fromJson<T, K>(dynamic json) {
  if (json is Iterable) {
    return _fromJsonList<K>(json) as T;
  } else if (T == LoginDetails) {
    return LoginDetails.fromJson(json) as T;
  } else if (T == UserDetails) {
    return UserDetails.fromJson(json) as T;
  } else if (T == Message) {
    return Message.fromJson(json) as T;
  } else {
    throw Exception("Unknown class");
  }
}

static List<K> _fromJsonList<K>(List jsonList) {
  if (jsonList == null) {
    return null;
  }

  List<K> output = List();

  for (Map<String, dynamic> json in jsonList) {
    output.add(fromJson(json));
  }

  return output;
}

然后您的函数最终看起来像这样:

class Network {
  /// If T is a List, K is the subtype of the list.
  Future<T> _getRequest<T, K>() async {
    print("entered");
    final response = await client
      .get("http://api.themoviedb.org/3/movie/popular?api_key=$_apiKey");
    print(response.body.toString());
    if (response.statusCode == 200) {
      // If the call to the server was successful, parse the JSON
    return fromJson<T, K>(json.decode(response.body));
  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
}

例如,如果您希望响应是一条消息,请致电_getRequest<Message, Null>()。如果您希望收到邮件列表,请致电_getRequest<List<Message>, Message>()