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

Flutter中如何使用Beamer包在导航时传递参数?

Beamer导航传参给NewBookingPage的两种方案

方案一:使用查询参数

跳转代码修改

在路由地址后拼接查询参数,直接传递字符串类型参数:

Beamer.of(context).beamToNamed(
  '${path ?? 'home/start'}/booking?resourceType=your_target_type',
);

页面接收参数

有两种接收方式:

  1. 直接在页面build方法中读取查询参数
class NewBookingPage extends ConsumerWidget {
  const NewBookingPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 从BeamState中提取查询参数
    final resourceType = Beamer.of(context)
        .currentBeamLocation
        .state
        .queryParameters['resourceType'];
    
    // 后续业务逻辑使用resourceType参数
    return ...;
  }
}
  1. 在路由配置中解析参数,通过构造函数传入
    如果想保留原页面的构造函数传参方式,需要在Beamer的路由配置中提前解析参数:
// 假设你的BeamerDelegate配置如下
BeamerDelegate(
  locationBuilder: BeamerLocationBuilder(
    beamLocations: [
      // 自定义的BeamLocation,包含booking路由
      HomeStartLocation(),
    ],
  ),
)

// 在HomeStartLocation的buildPages方法中配置
class HomeStartLocation extends BeamLocation {
  @override
  List<BeamPage> buildPages(BuildContext context, BeamState state) {
    return [
      ...
      BeamPage(
        key: ValueKey('booking-page'),
        child: NewBookingPage(
          state.queryParameters['resourceType'],
        ),
      ),
      ...
    ];
  }

  @override
  List<String> get pathBlueprints => ['/home/start/booking'];
}

方案二:使用BeamState的data字段传参

这种方式适合传递复杂对象,不限于字符串类型。

跳转代码修改

通过beamToNamed的data参数传递数据:

Beamer.of(context).beamToNamed(
  '${path ?? 'home/start'}/booking',
  // 可以传递Map、自定义类实例等
  data: {'resourceType': 'your_target_type'},
);

页面接收参数

同样有两种方式:

  1. 直接在build方法中读取data
class NewBookingPage extends ConsumerWidget {
  const NewBookingPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final beamData = Beamer.of(context).currentBeamLocation.state.data as Map?;
    final resourceType = beamData?['resourceType'] as String?;
    
    // 使用参数
    return ...;
  }
}
  1. 路由配置中解析data传入构造函数
// 在对应的BeamLocation的buildPages中
BeamPage(
  key: ValueKey('booking-page'),
  child: NewBookingPage(
    (state.data as Map)?['resourceType'],
  ),
),

内容的提问来源于stack exchange,提问作者JAgüero

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 01:45:15