You need to enable JavaScript to run this app. Flutter WebView加载HTML时script含非英文报无效字符错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Flutter WebView加载HTML时script含非英文报无效字符错误如何解决

错误原因

Uri.dataFromString 方法默认采用ASCII编码处理内容,当HTML中包含非英文字符(如韩文、中文等)时,编码不匹配就会触发 Invalid argument (string): Contains invalid characters 报错。

解决方案

需要做两处修改即可兼容非英文内容:

  1. 调用Uri.dataFromString时显式指定UTF-8编码,需先导入dart:convert库
  2. 在HTML头部补充charset声明,确保WebView解析HTML时也采用UTF-8编码

修改后的完整代码如下:

// 顶部导入依赖
import 'dart:convert';
import 'dart:io';

// 原有方法修改后
String _customScriptHTML() {
  String iosSetting = '';

  if (Platform.isIOS) {
    iosSetting = 'min-width:${width}px;min-height:${height}px;';
  }

  return Uri.dataFromString('''
<html>
<header>
  <!-- 新增charset声明 -->
  <meta charset="UTF-8">
  <meta name='viewport' content='width=device-width, initial-scale=1.0, user-scalable=yes'>
</header>
<body style="padding:0; margin:0;">
    <div id='map' style="width:100%;height:100%;$iosSetting"></div>
    <script type="text/javascript" src='https://dapi.kakao.com/v2/maps/sdk.js?autoload=true&appkey=$kakaoMapKey'></script>
    <script>
    // 此处可正常写入非英文内容
    -----------------------------------------------------------------------------
    There is an error if there is a language other than English!    
    -----------------------------------------------------------------------------
    </script>
</body>
</html>
    ''', 
    // 新增encoding参数指定UTF-8编码
    mimeType: 'text/html', 
    encoding: utf8
  ).toString();
}

内容的提问来源于stack exchange,提问作者RaD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 06:51:06