You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter:解决“List<dynamic>不是Response<dynamic>子类型”错误

解决Flutter类型错误:‘List’ is not a subtype of type ‘Response’

错误根源

  1. 类型混淆:NetworkApiServices的getApi方法返回的是解析后的JSON数据(接口返回数组时为List<dynamic>),但你在TestRepository的textapi方法中错误地用Response类型变量接收,导致实际返回的List与声明的Response类型不匹配。
  2. 语法错误:PostModel类中使用了小写的string类型,Dart中类型名需首字母大写,应为String。

具体修正步骤

1. 修正PostModel类的语法错误

class PostModel {
  final int? id;
  final String? title; // 修正:string → String
  final String? body; // 修正:string → String

  PostModel({this.id, this.title, this.body});

  factory PostModel.fromJson(Map<String, dynamic> json) {
    return PostModel(
      id: json['id'] as int?,
      title: json['title'] as String?,
      body: json['body'] as String?,
    );
  }

  Map<String, dynamic> toJson() {
    return {'id': id, 'title': title, 'body': body};
  }
}

2. 修正TestRepository的类型错误

直接接收解析后的List数据,无需使用Response类型:

class TestRepository {
  final _apiService = Get.put(NetworkApiServices());

  Future<List<PostModel>> textapi() async {
    // 直接接收解析后的List,强制类型转换确保安全
    final data = await _apiService.getApi(AppUrl.BASE_URL2) as List;
    // 遍历List,将每个JSON对象转为PostModel
    return data.map((json) => PostModel.fromJson(json as Map<String, dynamic>)).toList();
  }
}

3. 可选:增强API响应处理的安全性

在NetworkApiServices的returnResponse方法中,可以增加类型判断,避免后续转换出错:

dynamic returnResponse(http.Response response) {
  switch (response.statusCode) {
    case 200:
      dynamic responseJson = jsonDecode(response.body);
      if (kDebugMode) {
        print(responseJson.toString());
      }
      return responseJson;
    case 400:
      dynamic responseJson = jsonDecode(response.body);
      if (kDebugMode) {
        print(responseJson.toString());
      }
      return responseJson;
    default:
      throw FetchDataExceptions('与服务通信出错,状态码:${response.statusCode}');
  }
}

关键说明

  • NetworkApiServices的getApi方法已经完成了网络响应的解析(通过jsonDecode),返回的是直接可用的JSON数据(List或Map),不需要再用Response类包裹。
  • Dart是强类型语言,变量声明的类型必须与实际赋值的类型一致,否则会触发类型转换错误。

内容的提问来源于stack exchange,提问作者ابراهيم عبد المنعم

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 23:22:13