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

使用dio/retrofit时,如何自动修改_dio.fetch的响应类型为List?

解决Retrofit生成代码泛型不匹配列表响应的问题

问题原因

你当前接口返回的是JSON数组,但方法返回类型用了HttpResponse<ResponseList>,Retrofit默认会把顶级JSON对象解析为Map<String, dynamic>,而数组需要明确指定泛型为List<具体模型>。

解决步骤

1. 定义单个列表项的数据模型

先创建对应数组中单个对象的模型类,确保配置好序列化注解:

import 'package:json_annotation/json_annotation.dart';

part 'dashboard_item.g.dart';

@JsonSerializable()
class DashboardItem {
  final String key1;
  final String key2;
  final String key3;

  DashboardItem({required this.key1, required this.key2, required this.key3});

  factory DashboardItem.fromJson(Map<String, dynamic> json) => _$DashboardItemFromJson(json);
  Map<String, dynamic> toJson() => _$DashboardItemToJson(this);
}

2. 修改接口方法的返回类型

把原来的Future<HttpResponse<ResponseList>>改成Future<HttpResponse<List<DashboardItem>>>,明确告诉Retrofit要解析成列表结构:

@RestApi(baseUrl: BuildConfig.SERVER)
abstract class GetApiService {
  factory GetApiService(Dio dio,{String baseUrl}) = _GetApiService;
  @GET(MainApi.baseData)
  @FormUrlEncoded()
  Future<HttpResponse<List<DashboardItem>>> getDashboardHomeResponse();
}

3. 重新生成代码

运行build_runner命令重新生成Retrofit相关代码:

flutter pub run build_runner build --delete-conflicting-outputs

生成后的_dio.fetch代码会自动使用List<dynamic>作为泛型,无需手动修改即可正常运行。

额外说明

如果你的ResponseList是自定义的包装类(比如包含列表和其他状态字段),但接口实际返回的是纯数组,那这个类就不适用当前场景,必须直接用List<具体模型>作为泛型。如果接口确实有包装结构(比如{"data": [ ... ]}),则需要调整模型类和返回类型对应包装结构。

内容的提问来源于stack exchange,提问作者Esmaeil Ahmadipour

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:48:24