Flutter使用Dio调用reqres.in接口无法获取响应如何解决?
问题解决说明
核心错误原因
你封装的Dio拦截器没有调用处理器的传递方法,导致请求流程被中断,这是请求卡住、拿不到返回结果的根本原因。
Dio的InterceptorsWrapper要求所有拦截回调必须调用对应处理器的方法,才能让请求、响应、错误的流程继续向下传递。你当前的三个拦截回调都没有执行该操作,请求发出后被拦截器阻塞,所以日志仅输出到请求环节就没有后续输出。
具体需要修改的代码
修改HttpService类中的initializeInterceptors方法,在每个拦截回调末尾添加对应handler的调用即可:
initializeInterceptors() { _dio?.interceptors.add(InterceptorsWrapper( onError: (dioError, errorInterceptorHandler) { print(dioError.message); // 向下传递错误 errorInterceptorHandler.next(dioError); }, onRequest: (requestOptions, requestInterceptorHandler) { print("${requestOptions.method} | ${requestOptions.path}"); print("No error, request is successful"); // 继续执行请求发送 requestInterceptorHandler.next(requestOptions); }, onResponse: (response, responseInterceptorHandler) { print(response.data); print("We have got the response"); // 向下传递响应结果 responseInterceptorHandler.next(response); } )); }
额外优化建议
- 可以将
HttpService类中的_dio属性改为late Dio _dio非空类型,避免后续调用时重复使用!强制解包,减少崩溃风险 - 可以在
getUser方法的开头调用setState更新isLoading状态,保证加载动画正常触发
内容的提问来源于stack exchange,提问作者Shreyansh Sharma
相关产品推荐
相关产品推荐

