You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter发起HTTP请求时出现Failed host lookup错误求助

问题描述

原本可以正常向服务器发送GET和POST请求,但再次运行代码时持续报错,更换不同URL也无法解决。报错信息为:Failed host lookup: 'swapi.dev'

报错日志

E/flutter ( 5388): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Failed host lookup: 'swapi.dev'
E/flutter ( 5388): #0      IOClient.send
package:http/src/io_client.dart:88
E/flutter ( 5388): <asynchronous suspension>
E/flutter ( 5388): #1      BaseClient._sendUnstreamed
package:http/src/base_client.dart:93
E/flutter ( 5388): <asynchronous suspension>
E/flutter ( 5388): #2      _withClient
package:http/http.dart:164
E/flutter ( 5388): <asynchronous suspension>

相关代码

GET请求函数

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

class _LinkedBankAccountsState extends State<LinkedBankAccounts> {
  
  Future<void>  fetchData() async{
    var url = Uri.parse('https://swapi.dev/api/people');
    var response = await http.get(url);
    print(response);
  
  }

调用函数的Widget

GestureDetector(
    onTap: fetchData,
    child: BankWidget(
         desc: 'details',
         title: 'people',
         imageUrl:'lib/assets/images/flipLogo.png',
         ),
  ),

完整Widget代码

// ignore_for_file: prefer_const_constructors

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../widgets/background-image.dart';
import '../widgets/actions.dart';
import '../widgets/linked_bank_item.dart';
import '../widgets/linked_bank_item.dart';

class LinkedBankAccounts extends StatefulWidget {
  const LinkedBankAccounts({super.key});

  @override
  State<LinkedBankAccounts> createState() => _LinkedBankAccountsState();
}

class _LinkedBankAccountsState extends State<LinkedBankAccounts> {
  
  Future<void>  fetchData() async{
    var url = Uri.parse('https://swapi.dev/api/people');
    var response = await http.get(url);
    print(response);
  
  }

  @override
  Widget build(BuildContext context) {
    const routeName = '/linked-banks';
    return Stack(
      children: [
        backgroundImage(),
        Scaffold(
          backgroundColor: Colors.transparent,
                 appBar: AppBar(
            backgroundColor: Colors.transparent,
            elevation: 0,
            leading: IconButton(
              onPressed: () {
                Navigator.pop(context);
              },
              icon: Icon(
                Icons.arrow_back_ios,
                color: Colors.white,
              ),
            ),
           
           
          ),
          body: SingleChildScrollView(
            child: SafeArea(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                Container(
                  padding: EdgeInsets.only(top: 20,left: 30,right: 35) ,
                  height: 200,
                  width: 400 ,
                  decoration: BoxDecoration(
                    color:Colors.grey[600]!.withOpacity(0.3),
                    borderRadius: BorderRadius.circular(16), 
                    boxShadow: [
                      BoxShadow(
                        color: Colors.white.withOpacity(0.1),
                        spreadRadius: 1,
                        blurRadius: 7,
                        offset: Offset(0, 3)
                      )
                    ]
                    ), 
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      
                      children: [
                        
                        Container(
                          width: 50,
                          height: 50,
                          decoration: BoxDecoration(
                            color: Color(0XFF00B686),
                            boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.1),
                              blurRadius: 8,
                              spreadRadius: 3,
                            )
                            ],
                            border: Border.all(
                              width: 1.5,
                              color: Colors.white,
                            ),
                            borderRadius: BorderRadius.circular(40)
        
                          ),
                
                          child: CircleAvatar(
                              backgroundImage: AssetImage('lib/assets/images/avatar.png') ,
                          ),
                        ),
                        
                        Column(
                          
                          children: [
                            const Text(
                              'STANLEY OMEJE',
                              style: TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                                fontSize: 18
                              ),
                            ),
                            SizedBox(height: 10,),
                            Row(
                              // ignore: prefer_const_literals_to_create_immutables
                              children: [
                                Icon(Icons.keyboard_double_arrow_right_outlined,color: Colors.white, size: 30,),
                                SizedBox(width: 10,),
                                Text(
                                  'stanzealot',
                                   style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 18
                                    ),
                                ),
                                SizedBox(width: 10,),
                                Icon(
                                  Icons.copy_outlined,
                                  color: Colors.white,
                                  
                                )
                              ],
                            ),

                            SizedBox(height: 10,),
                            Text(
                              "\N0.00",
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 18,
                                fontWeight: FontWeight.bold
                              ),
                              )
                          ],
                        )

                      ],
                    ),
                ),

                SizedBox(height:30),
              
                 Column(
                   children: [
                     SizedBox(
                      height: 400,
                       child: ListView(
                          scrollDirection: Axis.vertical,
                          
                          children: [
                            
                          
                        GestureDetector(
                          onTap: fetchData,
                          child: BankWidget(
                            desc: 'details',
                            title: 'people',
                            imageUrl:'lib/assets/images/flipLogo.png',
                          ),
                        ),
                
                ]
                ),
                     ),
                   ],
                 ),
              

                //

              ],) 
              ),
          ) ,
        )
      ],
    );
  }
}
解决方案

Failed host lookup本质是设备无法解析目标域名,以下是逐一排查修复步骤:

  1. 检查网络权限配置

    • 安卓项目:确保android/app/src/main/AndroidManifest.xml中添加网络权限:
      <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
      
    • iOS项目:确保ios/Runner/Info.plist中配置网络访问权限(iOS 10+默认允许,若启用ATS需添加):
      <key>NSAppTransportSecurity</key>
      <dict>
          <key>NSAllowsArbitraryLoads</key>
          <true/>
      </dict>
      
  2. 验证设备网络连接

    • 确认模拟器/真机已连接可用网络,用设备浏览器打开https://swapi.dev,确认能正常访问;
    • 模拟器可尝试重启,或切换网络类型(如WiFi转蜂窝数据)。
  3. 清除DNS缓存

    • 安卓:直接重启设备;
    • iOS:开启飞行模式10秒后关闭,或重启设备。
  4. 关闭代理设置
    若设备开启了代理,先关闭代理再测试,代理可能拦截或干扰域名解析。

  5. 优化代码异常处理
    在请求函数中添加捕获逻辑,避免崩溃并输出详细错误:

    Future<void> fetchData() async{
      try {
        var url = Uri.parse('https://swapi.dev/api/people');
        var response = await http.get(url);
        print(response);
      } catch (e) {
        print('请求失败:$e');
      }
    }
    
  6. 检查http包版本
    确保pubspec.yaml中http包为稳定版,可更新到最新稳定版:

    dependencies:
      http: ^1.1.0
    

内容的提问来源于stack exchange,提问作者Stanley Omeje

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 12:50:22