问题:flutter 无法加载局域网https图片
具体错误日志如下所示:
======== Exception caught by image resource service ================================================
The following HandshakeException was thrown resolving an image codec:
Handshake error in client (OS Error:
CERTIFICATE_VERIFY_FAILED: IP address mismatch(handshake.cc:393))
When the exception was thrown, this was the stack:
Image provider: CachedNetworkImageProvider("https://xxx/2025/02/21/1740130220197ODgmA_矩形567@2x.png", scale: 1.0)
Image key: CachedNetworkImageProvider("https://xxx//2025/02/21/1740130220197ODgmA_矩形567@2x.png", scale: 1.0)
分析
关键信息:Handshake error in client (OS Error:
CERTIFICATE_VERIFY_FAILED: IP address mismatch(handshake.cc:393))
主要是https的安全证书校验问题,而局域网的https是本地的,官方证书平台是无法进行证书认证的
解决方案
知道了原因,那么我们可以在证书验证时强制返回成功就可以,具体方案:
1、创建HttpOverride,并重写createHttpClient方法,当证书校验失败时强制返回true
import 'dart:io';
class MyHttpOverrides extends HttpOverrides{
@override
HttpClient createHttpClient(SecurityContext? context){
return super.createHttpClient(context)
..badCertificateCallback = (X509Certificate cert, String host, int port)=> true;
}
}
2、在runApp之前,将MyHttpOverrides 设置为全局的MyHttpOverrides
if (currentEnv == Env.DEV) {
//开发环境
HttpOverrides.global = MyHttpOverrides();
}
runApp(const MyApp());
注意:以便使用局域网ip的一般都是开发环境,所以最好在开发环境下使用此种方案,避免安全问题。