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

使用Injectable依赖注入时Dio拦截器未生效问题排查

问题分析与解决方案

核心问题

你代码中注册的是Dio自带的LogInterceptor,但自定义的拦截器类名为LogInterceptors(末尾多了个s),这是拦截器未执行的直接原因——相当于你压根没把自己写的拦截器加到Dio实例里。

修复步骤与示例

1. 修正拦截器注册代码

将TSApiDio中的拦截器替换为自定义的LogInterceptors:

@singleton
class TSApiDio extends DioForNative {
  TSApiDio() {
    _configureOptions();
    _configureInterceptors();
  }

  void _configureOptions() {
    options.baseUrl = TSNetworkConstants.baseNewsAPIUrl;
    options.connectTimeout = TSNetworkConstants.connectionTimeout;
    options.receiveTimeout = TSNetworkConstants.receiveTimeout;
    options.responseType = ResponseType.json;
  }

  void _configureInterceptors() {
    // 替换为自定义的LogInterceptors实例
    interceptors.add(LogInterceptors());
  }
}

2. 确保Injectable依赖生成正确

运行build_runner命令生成依赖注入代码:

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

3. 确保Retrofit接口使用注入的TSApiDio实例

定义Retrofit接口时,通过构造函数注入TSApiDio:

@RestApi(baseUrl: TSNetworkConstants.baseNewsAPIUrl)
abstract class NewsApi {
  // 使用注入的TSApiDio创建实例
  factory NewsApi(TSApiDio dio) => _NewsApi(dio);

  @GET('/top-headlines')
  Future<NewsResponse> getTopHeadlines(@Query('country') String country);
}

4. 依赖注入初始化与使用

在main函数中初始化依赖注入:

void main() async {
  configureDependencies();
  runApp(const MyApp());
}

在业务类中注入Retrofit接口并调用:

@injectable
class NewsRepository {
  final NewsApi _newsApi;

  NewsRepository(this._newsApi);

  Future<NewsResponse> fetchTopHeadlines() => _newsApi.getTopHeadlines('us');
}

额外检查点

  • 确认TSApiDio的@singleton注解生效,确保全局使用同一个Dio实例
  • 检查自定义LogInterceptors中的log方法是否能正常输出(需导入dart:developer的log函数)
  • 确保调用接口时使用的是通过依赖注入获取的NewsApi实例,而非手动创建的Dio实例

内容的提问来源于stack exchange,提问作者Naufal Rajabi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:55:13