flutter network_error ai_generated partial

NetworkError:主机 'example.com' 的 DNS 查找失败

NetworkError: DNS lookup failed for host 'example.com'

ID: flutter/networkerror-dns-lookup-failed

其他格式: JSON · Markdown 中文 · English
80%修复率
81%置信度
1证据数
2023-03-25首次发现

版本兼容性

版本状态引入弃用备注
Flutter 2.10 active
Flutter 3.0 active
Flutter 3.7 active

根因分析

设备无法将主机名解析为 IP 地址,原因是网络连接问题、DNS 配置错误或主机不可达。

English

The device could not resolve the hostname to an IP address due to network connectivity issues, incorrect DNS configuration, or the host being unreachable.

generic

官方文档

https://api.flutter.dev/flutter/dart-io/HttpClient-class.html

解决方案

  1. Check the device's network connectivity and retry with exponential backoff:
    import 'dart:io';
    
    Future<bool> checkConnectivity() async {
      try {
        final result = await InternetAddress.lookup('example.com');
        return result.isNotEmpty && result[0].rawAddress.isNotEmpty;
      } on SocketException catch (_) {
        return false;
      }
    }
  2. Use a custom DNS resolver or fallback to a different DNS server, e.g., Google's 8.8.8.8, by configuring the HttpClient:
    HttpClient client = HttpClient();
    client.findProxy = (uri) {
      return 'PROXY 8.8.8.8:53; DIRECT';
    };
  3. Implement a retry mechanism with a timeout and user-friendly error message:
    try {
      await http.get(Uri.parse('https://example.com')).timeout(Duration(seconds: 10));
    } on SocketException {
      // show error to user
    }

无效尝试

常见但无效的做法:

  1. Hardcoding IP addresses instead of hostnames 50% 失败

    IP addresses can change; not a scalable solution and may break on different networks.

  2. Disabling DNS resolution and using raw IP in the app code 60% 失败

    Same as above; also violates best practices and may cause security warnings.

  3. Assuming the error is always on the server side 40% 失败

    Often the client's DNS configuration or network is the issue; server may be fine.