Flutter Web中如何用http包处理net::ERR_TIMED_OUT超时错误?
Flutter Web中处理http请求net::ERR_TIMED_OUT错误的方案
问题根源
你的代码存在两个核心问题导致超时无法被捕获,甚至请求本身异常:
- http.Client默认无超时限制,请求卡住后不会主动抛出错误,造成调试器冻结
- POST请求的参数被放在URL的query部分,不符合POST请求规范,可能导致服务器无法正确处理请求,进而引发超时
具体修复步骤
1. 给请求添加超时限制
用Future.timeout()包裹http请求,设置合理的超时时间(比如10秒),超时后会抛出TimeoutException,可被catch块捕获处理。
2. 修正POST请求参数传递方式
POST请求的参数应放在请求body中,而非URL的query参数里,否则服务器可能无法解析,导致请求耗时过长甚至超时。
3. 区分错误类型精准处理
不要将所有错误都归类为网络连接失败,需根据错误类型分别抛出对应异常,方便上层逻辑处理。
修复后的代码示例
Future<Session> login(String username, String password) async { final request = Uri.https(_baseUrlGeocoding, '/login'); try { // 添加10秒超时限制 final response = await _httpClient.post( request, // POST参数放在body中,用json格式传递 body: jsonEncode({ 'email': username.trim(), 'password': password, }), headers: {'Content-Type': 'application/json'}, ).timeout(const Duration(seconds: 10)); if (response.statusCode != 200) { throw LoginRequestServerFailure(); } final responseJson = jsonDecode(response.body) as Map<String, dynamic>; if (responseJson['message'] != 'OK') throw LoginCredentialsFailure(); return Session.fromJson(responseJson['data'] as Map<String, dynamic>); } on TimeoutException { // 捕获超时错误 print('请求超时'); throw RequestTimeoutFailure(); } on SocketException { // 捕获网络连接错误 print('网络连接异常'); throw InternetConnectionFailure(); } catch (error) { // 其他错误 print(error.toString()); throw LoginRequestServerFailure(); } }
额外排查点
- 确认服务器地址
_baseUrlGeocoding正确,且服务器在公网可访问 - 检查服务器是否配置了正确的CORS策略(Flutter Web跨域请求需要服务器允许)
- 测试服务器接口本身的响应速度,若服务器处理请求耗时过长,需优化后端逻辑
内容的提问来源于stack exchange,提问作者zex_rectooor
相关产品推荐
相关产品推荐

