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

Flutter+FastAPI项目真机无法调用接口,登录无响应求助

Flutter真机无法调用本地FastAPI后端,登录无响应排查方案

1. 修正API地址配置

模拟器可通过localhost或127.0.0.1访问本地后端,但真机必须使用电脑的局域网IP地址:

  • 查看电脑局域网IP:
    • Windows:执行命令 ipconfig,找到无线/以太网适配器的IPv4地址(如192.168.1.105)
    • Mac/Linux:执行命令 ifconfig 或 ip addr 获取对应网卡IP
  • 将Flutter中API请求地址从http://localhost:8000/login改为http://[你的电脑IP]:8000/login

2. 调整FastAPI启动绑定地址

默认FastAPI仅绑定127.0.0.1,仅本地可访问,需修改启动命令让后端监听所有网卡:

uvicorn main:app --host 0.0.0.0 --port 8000

3. 配置Android明文HTTP访问权限

Android 9+默认禁止明文HTTP请求,需添加网络安全配置:

  1. 在android/app/src/main/res/xml目录下创建network_security_config.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">你的电脑局域网IP</domain>
    </domain-config>
</network-security-config>
  1. 在AndroidManifest.xml的<application>标签中添加配置:
android:networkSecurityConfig="@xml/network_security_config"

4. 验证端口连通性

  • 在手机浏览器中访问http://[你的电脑IP]:8000/docs,若能打开FastAPI的Swagger文档,说明后端可正常访问;若无法打开,排查:
    • 电脑端是否有第三方防火墙拦截端口(即使关闭Windows Defender,也要检查其他安全软件)
    • 确认FastAPI服务正常运行,端口未被其他程序占用

5. 查看真机调试日志

点击登录无反馈可能是异常未被捕获,可通过以下方式查看日志:

  • 执行命令 flutter logs 实时查看真机调试输出
  • 在Android Studio/VSCode的Logcat面板中,过滤Flutter标签,查找网络请求相关异常信息

6. 再次确认网络权限

确保AndroidManifest.xml中已添加网络权限:

<uses-permission android:name="android.permission.INTERNET"/>

内容的提问来源于stack exchange,提问作者ZAYAHAN HASAN SHAH

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 10:24:58