flutter 無(wú)法加載局域網(wǎng)https圖片

問(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)題。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容