首页 > 解决方案 > 当我设置超时持续时间时,未处理的套接字异常没有互联网连接

问题描述

我使用简单的方法从 Internet 'http get request' 获取一些数据:

     `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;
      }
      }` 

但是当我没有互联网连接时,它会向我显示该错误:

 `Exception has occurred.
    SocketException (SocketException: Failed host lookup: 
    'jsonplaceholder.typicode.com' (OS Error: No address associated with 
    hostname, errno = 7))`

每当我删除 .timeout(Duration(seconds:5)) 时,代码都可以正常工作,但是在很长一段时间(15-20)秒后捕获了套接字异常,以表明没有互联网连接,这就是我使用超时的原因,我试过了要使用多个包(http 中间件、http 助手、重试),我尝试使用 http.client 并在 finally 块中关闭它,并且发生相同的错误并且应用程序崩溃

该图显示了抛出和未处理套接字异常时的错误

它按预期捕获了超时异常,但又过了 10-15 秒后,它抛出了一个已处理的套接字异常,为什么它会抛出这个套接字异常,我该怎么做才能避免这种情况?

标签: flutterdartunhandled-exceptionsocketexceptiontimeoutexception

解决方案


如果你想用 http 包实现超时,可以这样做:

import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:http/io_client.dart' as http;

Future<void> login(String email, String password) async {
    final ioClient = HttpClient();
    client.connectionTimeout = const Duration(seconds: 5);
    final body = { 'email': email, 'password': password };
    final client = http.IOClient(ioClient);
    http.Response res;
    try {
      res = await client
        .post(
          '$url/login',
          headers: {'Content-Type': 'application/json'},
          body: jsonEncode(body));
    } on SocketException catch (e) {
      // Display an alert, no internet
    } catch (err) {
      print(err);
      return null;
    }

    // Do something with the response...
}

推荐阅读