Flutter 设置超时持续时间时未处理的套接字异常,没有internet连接

Flutter 设置超时持续时间时未处理的套接字异常,没有internet连接,flutter,dart,unhandled-exception,socketexception,timeoutexception,Flutter,Dart,Unhandled Exception,Socketexception,Timeoutexception,我使用简单的方法从internet“http get请求”获取一些数据: `Future<UserModel> getUser(int userId) async { UserModel user; try { final response = await http.get( "$_baseUrl/users/$userId", ) .timeout

我使用简单的方法从internet“http get请求”获取一些数据:

     `Future<UserModel> getUser(int userId) async {
       UserModel user;
       try {
            final response = await http.get(
             "$_baseUrl/users/$userId",
           )
             .timeout(Duration(seconds: 5))

            ;
         user = userModelFromJson(response.body);
       return user;
      } on TimeoutException catch (e) {
       print('$e in authentication service');
     throw e;
      } on SocketException catch (e) {
     print('$e in authentication service');
     throw e;
     } catch (e) {
     print('$e in authentication service');
    throw e;
      }
      }` 
每当我删除.timeout(持续时间(秒:5))时,代码都能正常工作, 但套接字异常在长时间(15-20)秒后被捕获,以显示没有internet连接。这就是为什么我使用超时,我尝试使用多个包(http中间件、http帮助程序、重试),我尝试使用http.client并在finally块中关闭它,出现了相同的错误,应用程序崩溃


如预期的那样捕获超时异常,但是在10-15秒之后,它抛出一个处理套接字异常,它为什么抛出这个套接字异常,我能做些什么来避免这个?

您应该考虑使用HTTP包。 因为它有助于清理代码,所以有助于错误处理

下面是使用包的GET请求示例:

await http.get(url).then((response) async {
 // DO SOMETHING HERE
});
response.body是您的数据。 response.statusCode是您的http状态代码(200、404、500等)

下面是一个包含数据的post请求:

var data = {
      "dataset1": {
        "key1": "value",
        "key2": "value",
      },
    };
await http.post(url,
  body: jsonEncode(data),
  headers: {'content-type': 'application/json'}).then((response) async {
    // DO SOMETHING HERE
});

如果您想使用http包实现超时,下面是如何实现的:

导入'dart:io';
将“package:http/http.dart”导入为http;
将“package:http/io_client.dart”导入为http;
未来登录(字符串电子邮件、字符串密码)异步{
final ioClient=HttpClient();
client.connectionTimeout=常量持续时间(秒:5);
最终正文={'email':email,'password':password};
最终客户端=http.IOClient(IOClient);
http.res;
试一试{
res=等待客户机
.邮政(
“$url/login”,
标题:{'Content-Type':'application/json'},
正文:JSONECODE(正文);
}关于SocketException捕捉(e){
//显示警报,无internet连接
}捕捉(错误){
打印(错误);
返回null;
}
//对回应做点什么。。。
}

这是我已经做过的,http.get()部分来自http包,问题是当我使用get methodOops超时时,未处理的套接字异常对不起!我没有正确理解你的问题!没关系,我想你有什么想法请分享,但是你真的能在try/catch中捕捉到异常吗?看起来我和你有同样的错误,但对我来说,这个错误只被VSCode捕获(根据你链接的图片)@Gpack是对的在android studio尝试你的代码它会工作的
var data = {
      "dataset1": {
        "key1": "value",
        "key2": "value",
      },
    };
await http.post(url,
  body: jsonEncode(data),
  headers: {'content-type': 'application/json'}).then((response) async {
    // DO SOMETHING HERE
});