You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter GoRouter如何传递多参数?含Function与bool类型参数

GoRouter Web场景传递多参数(含Function与bool)

一、bool类型参数传递

bool参数可通过查询参数或路径参数传递,这类参数会被序列化为字符串,完全适配Web场景。

1. 查询参数方式

路由定义

GoRoute(
  path: '/edit-customer',
  builder: (context, state) {
    // 将字符串格式的查询参数转为bool类型
    final edit = state.queryParameters['edit'] == 'true';
    return EditCustomerPage(
      edit: edit,
      updateTab: // 后续处理Function参数
    );
  },
)

跳转调用

// 传递bool参数为true
context.go('/edit-customer?edit=true');
// 传递bool参数为false
context.go('/edit-customer?edit=false');

2. 路径参数方式

如果bool参数属于页面路径的固定组成部分,可采用路径参数:

路由定义

GoRoute(
  path: '/edit-customer/:edit',
  builder: (context, state) {
    final edit = state.pathParameters['edit'] == 'true';
    return EditCustomerPage(
      edit: edit,
      updateTab: // 后续处理Function参数
    );
  },
)

跳转调用

context.go('/edit-customer/true');

二、Function类型参数传递

Web场景下,GoRouter的路由参数(查询、路径参数)必须是可序列化类型,而Function无法序列化,因此不能直接通过路由参数传递,推荐以下两种方案:

1. 状态管理工具(推荐,兼容Web刷新)

使用Riverpod、Provider等状态管理工具存储回调函数,跳转前注册,目标页面读取。

步骤1:定义状态Provider

// 以Riverpod为例,Provider用法类似
final updateTabCallbackProvider = StateProvider<Function?>((ref) => null);

步骤2:跳转前注册回调

// 在跳转页面设置回调逻辑
ref.read(updateTabCallbackProvider.notifier).state = () {
  // 这里是updateTab的具体业务逻辑,比如切换tab
  print('执行tab切换');
};
// 同时传递bool参数
context.go('/edit-customer?edit=true');

步骤3:目标页面读取回调

修改EditCustomerPage,去掉构造函数中的updateTab参数,改为从状态管理读取:

class EditCustomerPage extends StatefulWidget {
  final bool edit;

  const EditCustomerPage({
    Key? key,
    required this.edit,
  }) : super(key: key);

  @override
  _EditCustomerPageState createState() => _EditCustomerPageState();
}

class _EditCustomerPageState extends State<EditCustomerPage> {
  late Function updateTab;

  @override
  void initState() {
    super.initState();
    // 从Provider读取回调函数
    updateTab = ref.read(updateTabCallbackProvider)!;
    // 读取后清空回调,避免内存泄漏
    ref.read(updateTabCallbackProvider.notifier).state = null;
  }

  @override
  Widget build(BuildContext context) {
    // 调用回调示例
    return ElevatedButton(
      onPressed: () => updateTab(),
      child: Text('执行回调'),
    );
  }
}

2. GoRouter extra参数(仅限非刷新场景)

extra参数可传递任意对象,但Web场景下刷新页面后extra会丢失(无法序列化存储),仅适合不需要刷新的临时跳转场景。

路由定义

GoRoute(
  path: '/edit-customer',
  builder: (context, state) {
    final edit = state.queryParameters['edit'] == 'true';
    // 从extra中取出Function
    final updateTab = state.extra as Function;
    return EditCustomerPage(
      edit: edit,
      updateTab: updateTab,
    );
  },
)

跳转调用

context.go(
  '/edit-customer?edit=true',
  extra: () {
    // updateTab的具体业务逻辑
    print('执行tab切换');
  },
);

注意事项

  • Web场景下禁止将Function序列化为字符串传递(比如通过查询参数),会触发运行时错误。
  • 使用状态管理方案时,需在页面销毁或读取回调后清空数据,避免内存泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 10:22:48