【问题标题】:Flutter: How to make a generic method with dynamically passed objectFlutter:如何使用动态传递的对象制作通用方法
【发布时间】:2020-07-22 15:31:47
【问题描述】:

我在颤振中有以下代码。它按预期工作。我有一个服务类。它有一个 getList 方法。该方法返回一个用户列表。

import 'package:http/http.dart' as http;
const ROOT = 'http://localhost/app/users.php';

class User{
  final String id;
  final String name;
  User({
    this.id,
    this.name,
  });

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      id: json['id'] as String,
      name: json['name'] as String,
    );
  }
  
}

class Services {

Future<List<User>> getList() async {
    try {
      var map = new Map<String, dynamic>();
      map["action"] = "fetch-all";
      final response = await http.post(ROOT, body: map);
      if (response.statusCode == 200) {
        final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
        List<User> list = parsed.map<User>((json) => User.fromJson(json)).toList();
        return list;
      } else {
        throw List<User>();
      }
    } catch (e) {
      return List<User>();
    }
  }

}

我正在尝试从上面的代码中创建一个通用方法。我可以在 getList() 方法中传递任何对象类型(例如:上述代码中的用户)作为参数,并获取此对象作为参数传入的输出列表。

例如:代替用户对象可以传递专辑对象作为参数,我可以获得专辑列表作为输出。

可能是这样的方法:

  Future<List> getList({Map map, MyClass}) async {
    final response = await http.post(ROOT, body: map);
    print("getUsers >> Response:: ${response.body}");
    if (response.statusCode == 200) {
      final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
      return parsed.map<MyClass>((json) => User.fromJson(json)).toList();
    } else {
      print("no data");
      throw List<MyClass>();
    }
  }

这里的MyClass是一个可以传递的动态Object。

【问题讨论】:

    标签: flutter


    【解决方案1】:

    试试这个:

    class Services {
    
      Future<List<T>> getList<T>() async {
        try {
          var map = new Map<String, dynamic>();
          map["action"] = "fetch-all";
          final response = await http.post(ROOT, body: map);
          if (response.statusCode == 200) {
            final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
            List<T> list = parsed.map<T>((json) => T.fromJson(json)).toList();
            return list;
          } else {
            throw <T>[];
          }
        } catch (e) {
          return <T>[];
        }
      }
    
    }
    

    【讨论】:

    • 工作,但无法访问 class T 的 fromJson 方法。它给出错误:The method fromJson isnt defined for type T.
    • 错误:方法 'fromJson' 没有为类 'Type' 定义。
    • 错误:方法 'fromJson' 没有为类 'Type' 定义``` 这行给出错误: List list = parsed.map((json) = > T.fromJson(json)).toList(); ```
    【解决方案2】:

    已解决:提示Dart, Can't call Generic's method

    在Services类的构造函数中传入fromJson方法。

    如下所示:

    class User{
      final String id;
      final String name;
      User({
        this.id,
        this.name,
      });
    
      factory User.fromJson(Map<String, dynamic> json) {
        return convertMaptoObject(json);
      }
    
      static toTypeObject(Map<String, dynamic> json) {
        return convertMaptoObject(json);
      }
    
      static convertMaptoObject(json) {
        return User(
          id: json['id'] as String,
          name: json['name'] as String,
        );
      }
      
    }
    
    class Services {
      final Function toTypeObject;
      final String path;
      final String action;
    
      Services({@required this.toTypeObject, @required this.path, this.action});
    
      Future<List<T>> getList<T>() async {
        try {
          var map = new Map<String, dynamic>();
          map["action"] = action == null ? 'fetch-all' : action;
          final response = await http.post(RESTAPI + path, body: map);
          print("getUsers >> Response:: ${response.body}");
          if (response.statusCode == 200) {
            print(response.body);
            var parsed = json.decode(response.body).cast<Map<String, dynamic>>();
            print(parsed);
            List<T> list = parsed.map<T>((json) => toTypeObject(json)).toList();
            return list;
          } else {
            throw <T>[];
          }
        } catch (e) {
          return <T>[];
        }
      }
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-20
      • 2020-04-15
      • 2021-04-28
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      • 2012-09-07
      • 1970-01-01
      相关资源
      最近更新 更多