問題: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、創(chuàng)建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) {
//開發(fā)環(huán)境
HttpOverrides.global = MyHttpOverrides();
}
runApp(const MyApp());
注意:以便使用局域網ip的一般都是開發(fā)環(huán)境,所以最好在開發(fā)環(huán)境下使用此種方案,避免安全問題。