如何彻底解决Android上的ERR_CLEARTEXT_NOT_PERMITTED错误?
问题解决方案
一、先修复当前Auth模拟器参数错误
你当前的核心报错Invalid authority field:[http: ]是因为useAuthEmulator方法的host参数不需要带http://前缀,直接传IP/域名即可。修改main.dart中的模拟器连接代码:
Future _connectToFirebaseEmulator() async { final localHostString = Platform.isAndroid ? '10.0.2.2' : 'localhost'; FirebaseFirestore.instance.settings = Settings( host: '$localHostString:2080', sslEnabled: false, persistenceEnabled: false, ); // 去掉http://前缀 await auth.FirebaseAuth.instance.useAuthEmulator(localHostString, 9080); }
二、彻底解决Cleartext流量问题
1. 修正network_security_config.xml配置
<domain>标签不能包含http://,仅保留IP/域名:
<?xml version="1.0" encoding="utf-8"?> <network-security-config xmlns:android="http://schemas.android.com/apk/res/android"> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">10.0.2.2</domain> <domain includeSubdomains="true">localhost</domain> </domain-config> </network-security-config>
确保该文件放在android/app/src/main/res/xml/目录下,文件名与引用一致。
2. 正确关联到AndroidManifest.xml
在<application>标签中添加网络配置引用,同时保留usesCleartextTraffic兜底:
<application android:label="mathems_m" android:name="${applicationName}" android:icon="@mipmap/ic_launcher" android:usesCleartextTraffic="true" android:networkSecurityConfig="@xml/network_security_config" android:roundIcon="@android:interpolator/cycle" android:supportsRtl="true" android:allowBackup="true"> <!-- 其他内容不变 --> </application>
3. 检查targetSdkVersion
如果build.gradle中targetSdkVersion >=28,以上配置即可满足cleartext流量要求,无需额外操作。
三、解决Firestore/Auth模拟器用户找不到问题
Firebase控制台创建的用户属于线上生产环境,本地模拟器是独立的离线环境,无法直接使用线上用户。解决方式二选一:
- 方式1:在模拟器环境中注册测试用户,可在代码中临时添加(仅开发阶段使用):
if (useEmulator) { try { // 创建测试用户,已存在则忽略错误 await auth.FirebaseAuth.instance.createUserWithEmailAndPassword( email: "test_dev@example.com", password: "dev123456", ); } catch (e) { print("用户已存在或创建失败:$e"); } } - 方式2:用Firebase CLI导入用户到模拟器:
# 先准备包含用户信息的users.json文件,格式参考Firebase官方文档 firebase auth:import users.json --emulator
四、CLI配置Android模拟器网络安全(临时测试用)
如果不想修改代码配置,可通过adb命令临时允许cleartext流量(重启模拟器后失效):
# 清除代理并重置应用缓存 adb shell settings put global http_proxy :0 adb shell pm clear com.example.mathems_m # 开启应用调试模式(允许绕过部分网络安全限制) adb shell cmd package set-debug-app --enable com.example.mathems_m
五、验证步骤
- 启动Firebase模拟器:
firebase emulators:start - 修正代码后重新运行项目:
flutter run - 使用模拟器环境创建的测试用户登录,不要用控制台的线上用户
内容的提问来源于stack exchange,提问作者mathems32
相关产品推荐
相关产品推荐

