Flutter开发中Dio不发送请求卡在等待状态问题求助
问题核心原因排查&解决方案
1. 代码拼写错误(最优先排查)
Dart 是大小写敏感的语言,你提供的代码里存在两处致命拼写问题:
- 方法名不匹配:
AuthenticationService类中定义的方法名为大写开头的SignIn,但调用时使用的是小写开头的signIn,会直接抛出方法不存在的异常 - 参数名不匹配:方法定义时密码参数为大写开头的
Password,但请求传参时使用的是小写的password,会抛出变量未定义的异常
修正后的 AuthenticationService 代码如下:
class AuthenticationService extends Service { // 方法名、参数名统一为小写开头,和调用逻辑匹配 Future<String?> signIn({String? email, String? password}) async { Response? response; try { response = await http.post('/auth/login', data: { 'email': email, 'password': password }); } catch(e) { print('登录请求出错: $e'); rethrow; // 将异常抛给上层,避免静默失败 } return response?.data.toString(); } }
2. Dio 未配置超时时间
默认 Dio 没有请求超时限制,如果网络链路不通,请求会无限挂起,既不会进 catch 也不会返回,导致后续代码永远不执行。你需要给 Dio 实例加上超时配置:
class Service { Dio http = Dio( BaseOptions( baseUrl: 'http://10.0.2.2/api', connectTimeout: Duration(seconds: 10), // 连接超时10秒 receiveTimeout: Duration(seconds: 10), // 接收数据超时10秒 sendTimeout: Duration(seconds: 10), // 发送数据超时10秒 ), ); }
3. Provider 注册配置错误
如果注册 Provider 时注册的是父类 Service,而非子类 AuthenticationService,调用 context.read<AuthenticationService>() 时会抛出找不到实例的异常,中断代码执行。需要确保注册类型和读取类型一致:
// 注册时直接声明为 AuthenticationService 类型 MultiProvider( providers: [ Provider<AuthenticationService>(create: (context) => AuthenticationService()), ], child: const MyApp(), )
4. 调用位置未捕获异常
如果上层调用登录方法的位置没有做异常捕获,只要过程中抛出任何未处理异常,都会直接中断执行,后续的 print 自然不会打印。修改调用逻辑添加异常捕获:
print('Passed!'); try { await context.read<AuthenticationService>().signIn( email: _emailController.text, password: _passwordController.text, ); print('Passed?'); } catch (e) { print('调用登录方法异常: $e'); }
额外注意项
http://10.0.2.2 是 Android 模拟器专属的本地主机映射地址,如果你使用 iOS 模拟器、真机测试,需要将 baseUrl 替换为电脑所在局域网的实际 IP 地址(如 http://192.168.3.4/api 格式),否则会出现网络不通的问题。
内容的提问来源于stack exchange,提问作者Heaven Aldrico
相关产品推荐
相关产品推荐

