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

dan*_*anu 4 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');
  }
 }
Run Code Online (Sandbox Code Playgroud)

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

 getAllList(){
  return _getRequest(dataModel);
 }
Run Code Online (Sandbox Code Playgroud)

Ovi*_*diu 6

下面的解决方案适用于通用对象以及通用对象列表(来自 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 if (T == bool || T == String || T == int || T == double || T == Map) { // primitives
    return json;
} else {
    throw Exception("Unknown class");
  }
}

static List<K> _fromJsonList<K>(List<dynamic> jsonList) {
  return jsonList?.map<K>((dynamic json) => fromJson<K, void>(json))?.toList();
}
Run Code Online (Sandbox Code Playgroud)

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

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');
  }
}
Run Code Online (Sandbox Code Playgroud)

例如,如果您希望响应是消息,则可以调用_getRequest<Message, Null>(). 如果您需要消息列表,您可以调用_getRequest<List<Message>, Message>().