You need to enable JavaScript to run this app. 如何在Flutter中使用Retrofit实现API请求、响应处理与基础认证?
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter中使用Retrofit实现API请求、响应处理与基础认证?

Flutter Retrofit 常见请求实现指南

(基于你已配置的依赖和基础ApiClient结构)

前置提醒

所有新增的请求方法、实体类编写完成后,需要在项目根目录运行以下命令重新生成代码:
flutter pub run build_runner build --delete-conflicting-outputs
生成完成后即可直接使用ApiClient实例调用对应方法。


1. 编写GET请求

Retrofit通过@GET注解标记请求路径,支持两种常用参数形式:

  • @Query("参数名"):自动将参数拼接到URL的查询串后,对应?key=value格式
  • @Path("占位符"):替换URL路径中的动态占位符

代码示例

直接在已有的ApiClient抽象类中添加方法:

@RestApi(baseUrl: "https://gorest.co.in/public-api/")
abstract class ApiClient {
  factory ApiClient(Dio dio, {String baseUrl}) = _ApiClient;

  // 带分页查询参数的GET:获取用户列表
  @GET("/users")
  Future getUsers([@Query("page") int page = 1, @Query("per_page") int perPage = 10]);

  // 带路径参数的GET:获取单个用户详情,路径中的{id}会被自动替换
  @GET("/users/{id}")
  Future getUserDetail(@Path("id") int userId);
}

2. 编写POST请求与请求体传参

POST请求通过@POST注解标记路径,最常用的传参方式是用*@Body*注解标注实体类作为请求体,Retrofit会自动将实体类序列化为JSON,自动设置Content-Type: application/json请求头。

实现步骤

  1. 先编写对应请求的实体类(搭配json_serializable自动生成序列化代码):
// create_user_request.dart
import 'package:json_annotation/json_annotation.dart';
part 'create_user_request.g.dart';

@JsonSerializable()
class CreateUserRequest {
  final String name;
  final String email;
  final String gender;
  final String status;

  CreateUserRequest({
    required this.name,
    required this.email,
    required this.gender,
    required this.status,
  });

  factory CreateUserRequest.fromJson(Map<String, dynamic> json) => _$CreateUserRequestFromJson(json);
  Map<String, dynamic> toJson() => _$CreateUserRequestToJson(this);
}
  1. 在ApiClient中添加POST方法:
//  POST请求:创建用户,直接将实体类作为请求体传入
@POST("/users")
Future createUser(@Body CreateUserRequest request);

如果需要发送表单格式的POST请求,可以搭配*@FormUrlEncoded注解和@Field*注解使用,但目前绝大多数接口都使用JSON格式传参,用@Body即可满足需求。

3. 处理API返回的响应数据

不推荐所有接口都用dynamic作为返回类型,手动解析JSON会增加冗余代码,可以定义通用的响应包裹类,让Retrofit自动完成JSON转实体类的过程。

实现逻辑

  1. 先定义匹配后端返回结构的通用响应类(以gorest的返回结构为例:包含code、data、meta三个字段):
@JsonSerializable(genericArgumentFactories: true)
class ApiResponse<T> {
  final int code;
  final T? data;
  final Map<String, dynamic>? meta;

  ApiResponse({required this.code, this.data, this.meta});

  factory ApiResponse.fromJson(Map<String, dynamic> json, T Function(Object? json) fromJsonT) =>
      _$ApiResponseFromJson(json, fromJsonT);
}
  1. 将之前的接口返回类型替换为对应的强类型,比如把获取用户列表的返回类型改为Future<ApiResponse<List<User>>>,Retrofit会自动完成全部JSON解析工作,不需要手动调用jsonDecode。
  2. 异常处理:因为Retrofit是基于Dio封装的,所有网络错误、服务端错误、参数错误都会被包装为DioError抛出,不需要在接口方法内部写异常捕获,在调用接口的位置统一处理即可:
try {
  final resp = await apiClient.getUsers();
  if (resp.code == 200) {
    // 直接使用结构化的data字段,不需要手动解析
    final userList = resp.data;
  }
} on DioError catch (e) {
  // 统一处理错误:e.response?.data 为后端返回的错误信息,e.type 为错误类型(连接超时、无网络、服务端500等)
}

4. 配置Retrofit的基础认证(Basic Authentication)

基础认证不需要在每个请求方法中单独添加请求头,通过Dio拦截器统一配置即可,所有通过该Dio实例发出的请求都会自动带上认证头。

实现步骤

在初始化Dio实例时添加认证拦截器:

import 'dart:convert';

// 初始化Dio
final dio = Dio(BaseOptions(
  baseUrl: "https://gorest.co.in/public-api/",
  connectTimeout: 5000,
  receiveTimeout: 5000,
));

// 添加Basic认证拦截器
dio.interceptors.add(InterceptorsWrapper(
  onRequest: (options, handler) {
    // Basic认证的格式为 'Basic base64(账号:密码)'
    const username = "你的认证账号";
    const password = "你的认证密码";
    final authValue = "Basic ${base64Encode(utf8.encode('$username:$password'))}";
    options.headers["Authorization"] = authValue;
    // 继续执行请求流程
    return handler.next(options);
  },
));

// 将配置好的Dio传入ApiClient,所有请求自动携带认证头
final apiClient = ApiClient(dio);

如果有个别公开接口不需要携带认证头,可以在拦截器的onRequest中添加路径判断,跳过对应路径的认证头设置。


内容的提问来源于stack exchange,提问作者Dhyan V

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.12 06:06:04