Flutter WebView加载HTML时script含非英文报无效字符错误如何解决
错误原因
Uri.dataFromString 方法默认采用ASCII编码处理内容,当HTML中包含非英文字符(如韩文、中文等)时,编码不匹配就会触发 Invalid argument (string): Contains invalid characters 报错。
解决方案
需要做两处修改即可兼容非英文内容:
- 调用
Uri.dataFromString时显式指定UTF-8编码,需先导入dart:convert库 - 在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
相关产品推荐
相关产品推荐

