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

Flutter TypedGoRoute如何实现extra参数的代码生成支持?

关于TypedGoRoute扩展支持extra参数的实现方案

问题描述

我们项目使用TypedGoRoute定义路由,相关代码如下:

路由定义

TypedGoRoute<MyScreenRoute>(path: 'my_route_name')

路由数据类

class MyScreenRoute extends GoRouteData {

  const MyScreenRoute({
    this.initialValue = 0,
  });

  final int initialValue;
  @override
  Widget build(final BuildContext context, final GoRouterState state) =>
      MyScreen(
        models: state.extra! as List<MyCustomClass>,
        initialValue: initialValue,
      );
}

当前跳转调用

const MyScreenRoute(initialValue: 5).push<void>(context);

目前传递initialValue这类基础类型参数正常,但代码生成的.go和.push方法仅包含location和queryParams,未支持extra参数。希望实现如下调用方式,询问是否可行:

const MyScreenRoute(initialValue: 5).push<void>(context, myListOfCustomObjects);

解决方案

可行,无需修改代码生成逻辑,通过扩展GoRouteData即可实现需求。

方式一:自定义带extra的push方法

创建扩展类,为GoRouteData新增支持extra参数的方法:

extension GoRouteDataExtraExtension on GoRouteData {
  Future<T?> pushWithExtra<T>(BuildContext context, Object? extra) {
    return context.goRouter.push<T>(location, extra: extra);
  }
}

调用时使用该自定义方法:

const MyScreenRoute(initialValue: 5).pushWithExtra<void>(context, myListOfCustomObjects);

方式二:扩展原push方法兼容extra参数

如果想完全贴合你想要的调用格式,可以通过可选位置参数扩展原push方法:

extension GoRouteDataExtraExtension on GoRouteData {
  Future<T?> push<T>(BuildContext context, [Object? extra]) {
    return context.goRouter.push<T>(location, extra: extra);
  }
}

这样就能直接使用目标调用方式:

const MyScreenRoute(initialValue: 5).push<void>(context, myListOfCustomObjects);

原理很简单,GoRouter本身的push方法就支持extra参数,只是TypedGoRoute的代码生成没有封装该参数,通过扩展可以快速补上这个能力,且不会影响原有代码的正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 10:14:52