【问题标题】:Unhandled Exception Future dynamic is not a subtype of type FutureOr List Books未处理的异常未来动态不是 FutureOr List Books 类型的子类型
【发布时间】:2020-05-11 10:48:36
【问题描述】:

如何将Future<dynamic>的数据传递给Future<List<dynamic>>

getall(BuildContext context, String url, String type) async {
  final response = await http.get(url, headers: { 
 'Accept': 'application/json' 'Authorization': 'Bearer $token'
  });
if (response.statusCode == 200) {
  switch(type){
  case "Chapters":
            List responseJson = json.decode(response.body)['data'];
            return responseJson.map((m) => new Subjects.fromJson(m)).toList();
            break;
   case "Subjects":
            List responseJson = json.decode(response.body)['data'];
            return responseJson.map((m) => new Chapters.fromJson(m)).toList();
            break; 
 } 
}
}

这是我要从getall获取数据的函数:

Future<List<Subjects>> getsubjects(BuildContext context, String url, String type) async {
  return getall(context, url, type);

Future<List<Chapters>> getchapters(BuildContext context, String url, String type) async {
  return getall(context, url, type);
}

【问题讨论】:

    标签: asynchronous flutter dart


    【解决方案1】:

    getall 函数指定返回类型应该可以解决这个问题。

    Future<List<Subjects>> getall(BuildContext context, String url, String type) async {
      final response = await http.get(url, headers: {
        'Accept': 'application/json',
        'Authorization': 'Bearer $token'
      });
    
    
      if (response.statusCode == 200) {
        List responseJson = json.decode(response.body)['data'];
        return responseJson.map((m) => new Subjects.fromJson(m)).toList();
      }
    }
    
    

    【讨论】:

    • 你 100% 正确,但我想为不同的函数获取相同的数据,例如 Future&lt;List&lt;Chapters&gt;&gt; getchapters(BuildContext context, String url, String type) async { return getall(context, url, type); }
    • getall(BuildContext context, String url, String type) async { final response = await http.get(url, headers: { 'Accept': 'application/json', 'Authorization': 'Bearer $token' }); if (response.statusCode == 200) { List responseJson = json.decode(response.body)['data']; return responseJson.map((m) =&gt; new Subjects.fromJson(m)).toList(); } }
    猜你喜欢
    • 2021-05-05
    • 2021-09-16
    • 2021-04-04
    • 1970-01-01
    • 2022-09-26
    • 2023-02-26
    • 2021-09-07
    • 2021-08-15
    • 2023-04-03
    相关资源
    最近更新 更多