Flutter 嵌套H5 传参数

你可以通过在加载 H5 页面时,将 token 作为 URL 参数拼接,或者通过 WebView 的 JavaScript 通信功能(如 runJavaScriptaddJavaScriptChannel)传递 token。常用方式如下:

方式一:URL 拼接参数

假设你的 token 是 myToken,可以这样:

java 复制代码
// filepath: [home.dart](http://_vscodecontentref_/0)
class HomePage extends StatelessWidget {
  final String token;
  const HomePage({super.key, required this.token});

  @override
  Widget build(BuildContext context) {
    final url = 'https://www.baidu.com?token=$token';
    return Scaffold(
      appBar: AppBar(title: const Text('首页')),
      body: SafeArea(
        child: WebViewWidget(
          controller: WebViewController()
            ..setJavaScriptMode(JavaScriptMode.unrestricted)
            ..loadRequest(Uri.parse(url)),
        ),
      ),
    );
  }
}

方式二:通过 JavaScript 注入

如果不想暴露在 URL,可以在页面加载完成后注入 token:

java 复制代码
// filepath: [home.dart](http://_vscodecontentref_/1)
class HomePage extends StatelessWidget {
  final String token;
  const HomePage({super.key, required this.token});

  @override
  Widget build(BuildContext context) {
    final controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..loadRequest(Uri.parse('https://www.baidu.com'))
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageFinished: (url) {
            controller.runJavaScript("window.setToken && window.setToken('$token');");
          },
        ),
      );

    return Scaffold(
      appBar: AppBar(title: const Text('首页')),
      body: SafeArea(
        child: WebViewWidget(controller: controller),
      ),
    );
  }
}

这种方式需要 H5 页面实现 window.setToken 方法来接收 token。

你可以根据实际需求选择合适的方式。这种方式需要 H5 页面实现 window.setToken 方法来接收 token。

你可以根据实际需求选择合适的方式。

相关推荐
njxiejing15 分钟前
Python NumPy安装、导入与入门
开发语言·python·numpy
Rhys..34 分钟前
Python&Flask 使用 DBUtils 创建通用连接池
开发语言·python·mysql
土了个豆子的1 小时前
04.事件中心模块
开发语言·前端·visualstudio·单例模式·c#
老华带你飞1 小时前
考研论坛平台|考研论坛小程序系统|基于java和微信小程序的考研论坛平台小程序设计与实现(源码+数据库+文档)
java·vue.js·spring boot·考研·小程序·毕设·考研论坛平台小程序
CHEN5_021 小时前
leetcode-hot100 11.盛水最多容器
java·算法·leetcode
songx_991 小时前
leetcode18(无重复字符的最长子串)
java·算法·leetcode
@菜菜_达1 小时前
Lodash方法总结
开发语言·前端·javascript
GISer_Jing1 小时前
低代码拖拽实现与bpmn-js详解
开发语言·javascript·低代码
Zender Han1 小时前
Flutter 视频播放器——flick_video_player 介绍与使用
android·flutter·ios·音视频
@areok@2 小时前
C++mat传入C#OpencvCSharp的mat
开发语言·c++·opencv·c#