Flutter调用原生JS方法时怎么传参?

Newb.文茹 阅读 23

我在Flutter WebView里加载了一个本地HTML页面,想通过JavaScriptChannel调用JS函数并传个字符串参数过去,但JS那边收不到值,不知道是不是写法有问题。

试过这样写:

function receiveMessage(msg) {
  console.log('收到消息:', msg);
  document.getElementById('output').innerText = msg;
}

然后在Dart里用webViewController.runJavascript('receiveMessage("hello")')调用,结果控制台打印出来是undefined,元素也没更新,到底咋回事?

我来解答 赞 9 收藏
二维码
手机扫码查看
2 条解答
UI贝贝
UI贝贝 Lv1
这个问题我遇到过,核心是runJavascript是异步的,你没等它执行完。

正确的写法:

// 加上await
await webViewController.runJavascript('receiveMessage("hello")');


如果是在按钮点击事件里调用的,确保外层方法是async的:

ElevatedButton(
onPressed: () async {
await webViewController.runJavascript('receiveMessage("hello")');
},
child: Text('发送'),
)


另外提醒一下,webview_flutter 4.0之后evaluateJavascript已经废弃了,现在统一用runJavascript。

还有一个可能的坑:你的HTML是本地assets里的,加载需要时间。确保在WebViewController加载完成后再调用JS:

final controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..loadRequest(Uri.parse('file:///assets/html/index.html'));

await controller.setNavigationDelegate(
NavigationDelegate(
onPageFinished: (String url) {
// 页面加载完后再调用JS
controller.runJavascript('receiveMessage("hello")');
},
),
);


如果参数是动态的,记得字符串拼接时处理一下特殊字符,防止引号冲突导致语法错误。
点赞
2026-03-14 14:12
技术小利
参数被当成JS语句解析了,得用JSON.stringify转一下。这样改:

webViewController.runJavascript('receiveMessage(${jsonEncode('hello')})');


JS那边不用改,直接收字符串就行。Flutter这坑我踩过,参数得手动处理下。
点赞 2
2026-03-08 12:57