問(wèn)題:flutter 無(wú)法加載局域網(wǎng)https圖片
具體錯(cuò)誤日志如下所示:
======== 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)
分析
關(guān)鍵信息:Handshake error in client (OS Error:
CERTIFICATE_VERIFY_FAILED: IP address mismatch(handshake.cc:393))
主要是https的安全證書(shū)校驗(yàn)問(wèn)題,而局域網(wǎng)的https是本地的,官方證書(shū)平臺(tái)是無(wú)法進(jìn)行證書(shū)認(rèn)證的
解決方案
知道了原因,那么我們可以在證書(shū)驗(yàn)證時(shí)強(qiáng)制返回成功就可以,具體方案:
1、創(chuàng)建HttpOverride,并重寫(xiě)createHttpClient方法,當(dāng)證書(shū)校驗(yàn)失敗時(shí)強(qiáng)制返回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 設(shè)置為全局的MyHttpOverrides
if (currentEnv == Env.DEV) {
//開(kāi)發(fā)環(huán)境
HttpOverrides.global = MyHttpOverrides();
}
runApp(const MyApp());
注意:以便使用局域網(wǎng)ip的一般都是開(kāi)發(fā)環(huán)境,所以最好在開(kāi)發(fā)環(huán)境下使用此種方案,避免安全問(wèn)題。