我正在使用 go_router 9.0.1 和 go_router_builder 2.2.0 以及 Riverpod 2.3.6。 我已经在我的项目中实现了 go_router ,并且默认情况下,当使用转到子路由时,包会保持上一页的状态。就我而言,我希望每次进入一个页面时,该页面都会重新加载/重建。
例如我有 2 条路线:
page1
具有子路由,例如page1/sub1Page1
或 -page1/sub2Page1
page2
带有子路由,如page2/sub1Page1
或 -page2/sub2Page1
如果我使用 Page1().go(context)
方法从 page1
转到 page1/sub1Page1
因为我正在使用该类型安全的方法。我想从 page1/sub1Page1
返回到 page1
,其中 Page1().go(context)
我的 Riverpod 提供程序的状态是一样的。它将 Page1
小部件状态存储在某处,这意味着我需要在推送另一个页面之前使用 ref.invalidate(myProvider)
手动重置我的提供程序。是否存在实现此行为的解决方案?
我当前简化的 go_router 实现:
GoRouter(
routes: $appRoutes,
initialLocation: initialLocation,
debugLogDiagnostics: true,
);
@TypedShellRoute<HomeRoute>(
routes: <TypedRoute<GoRouteData>>[
TypedGoRoute<Page1Route>(
path: Page1Route.path,
name: Page1Route.name,
routes: <TypedGoRoute<GoRouteData>>[
TypedGoRoute<Sub1Page1>(
path: Sub1Page1.path,
name: Sub1Page1.name,
),
TypedGoRoute<Sub2Page1>(
path: Sub2Page1.path,
name: Sub2Page1.name,
),
]
TypedGoRoute<Page2>(
path: Page2.path,
name: Page2.name,
),
]);
class HomeRoute extends ShellRouteData {
const HomeRoute();
@override
Widget builder(BuildContext context, GoRouterState state, Widget navigator) =>
Layout(child: navigator);
}
class Page1 extends GoRouteData {
const ProjectsRoute();
static const String name = kNamePage1;
static const String path = kPathPage1 ;
@override
Widget build(BuildContext context, GoRouterState state) => Page1Screen();
}
// Note that all the page or subpage are declared exactly as above.
最佳答案
可以不维护页面的状态,但使用 go_router 包可以隐藏该功能。
在 MaterialApp
小部件参数 maintainState
可用。但由于我们使用 MaterialApp.router
该参数不再可用。
仅当我们尝试进行自定义转换时,它才会再次随包一起出现。 我们可以在文档中找到这个示例:
class FancyRoute extends GoRouteData {
@override
MaterialPage<void> buildPage(BuildContext context, GoRouterState state) =>
CustomTransitionPage<void>(
key: state.pageKey,
child: FancyPage(),
transitionsBuilder: (context, animation, animation2, child) =>
RotationTransition(turns: animation, child: child),
),
}
CustomTransitionPage
基于 MaterialPage
小部件又在这里 maintainState
属性可用,并且需要设置为 false,因为默认情况下它为 true。
如果您像我一样并且不希望页面之间有任何动画,请不要使用 NoTransitionPage<T> class
因为此参数不可用。
然后,我根据他们对无转换页面的实现创建了一个自定义页面,其中维护状态为 false。然后您可以按照 go router 包中的说明使用它。
/// Custom transition page with no transition.
class CustomNoTransitionPage<T> extends CustomTransitionPage<T> {
/// Constructor for a page with no transition functionality.
const CustomNoTransitionPage({
required super.child,
super.name,
super.arguments,
super.restorationId,
super.key,
}) : super(
transitionsBuilder: _transitionsBuilder,
transitionDuration: Duration.zero,
reverseTransitionDuration: Duration.zero,
maintainState: false,
);
static Widget _transitionsBuilder(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) =>
child;
}
关于flutter - (go-router) 转到上一页时刷新 Riverpod 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76653679/