0%

Flutter2报错 Bad state: Insecure HTTP is not allowed by platform

问题

在将Flutter项目升级到 Flutter 2 之后:

1
2
environment:
sdk: ">=2.12.0 <3.0.0"

发现在使用 dio 发起请求时遇到了App崩溃的问题。

调试发现请求发出后会一直卡住,没有发出请求,也没有报错信息提示(在 VS Code 中)。

后来我用 AS 重新创建了一个空项目只添加 dio 用来测试请求。发现 https 链接的请求正常,访问本地的 http 链接会报错。错误信息如下:

1
2
3
4
5
Reloaded 0 libraries in 47ms.
[VERBOSE-2:ui_dart_state.cc(186)] Unhandled Exception: DioError [DioErrorType.other]: Bad state: Insecure HTTP is not allowed by platform: http://172.21.40.40:9999/version
#0 _HttpClient._openUrl (dart:_http/http_impl.dart:2434:7)
#1 _HttpClient.openUrl (dart:_http/http_impl.dart:2341:7)
#2 De

如何解决

后来,在Flutter网站中搜索到相关的文档,给出了如下的解决方法。

Insecure HTTP connections are disabled by default on iOS and Android - Flutter

Android端

修改Flutter项目中 android/app/src/mian/AdnroidManifest.xml 文件:

1
2
3
4
5
6
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="io.flutter.app.FlutterApplication"
android:label="receipt"
android:usesCleartextTraffic="true"
android:icon="@mipmap/ic_launcher">

即在上面的 <application> 中添加 android:usesCleartextTraffic="true" 一行。

IOS端

在文件 ios/Runner/info.plist 中添加以下键值对:

1
2
3
4
5
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

重新运行项目后,测试能够正常访问本地的 http 链接了。


如有疑问或需要技术讨论,请留言或发邮件到 service@itfanr.cc