I want to mimic the TaskStackBuilder from the native Anrdroid (like this) using go_router in flutter.
Basically what I want is when a user access a deeplink from a route, he will be navigated to that screen while having a proper back stack. Say my route looks like the following:
GoRouter( routes: [ GoRoute( path: "/", name: AppRouteName.home builder: (context, routerState) { return const HomeScreen(); }, ), GoRoute( path: "/promo", name: AppRouteName.promo builder: (context, routerState) { return const ListPromoScreen(); }, routes: [ GoRoute( path: ":id, name: AppRouteName.promoDetail builder: (context, routerState) { return const PromoDetailScreen(routerState.id); } ), ] ), GoRoute( path: "/invoice", name: AppRouteName.invoice, builder: (context, routerState) { return ListInvoicesScreen(); }, ), GoRoute( path: "/changePassword", name: AppRouteName.changePassword, builder: (context, routerState) { return const ChangePasswordScreen(); }, ), ] )
I found that having back stack was achieveable by having nested routes as depicted by ListPromoScreen and PromoScreenDetail. But it would only gives the user a back stack only until ListPromoScreen (when there's a deeplink looks like packageName://app/promo:id), while what I want is the user to have the back stack until the HomeScreen .
I come to think that if we use sub routes/nested route from go_router, the router tree would be to deep since I have a sequencial flow which can consist of 4 sequentially connected screen / activity. I wouldn't think a nested routes is proper for this case.
Any suggestion?
Use a ShellRoute as the root so the deep link builds the full hierarchy stack automatically instead of manually pushing routes:
final router = GoRouter(
routes: [
ShellRoute(
builder: (context, state, child) => HomeScreen(child: child),
routes: [
GoRoute(
path: '/promo',
builder: (context, state) => const ListPromoScreen(),
routes: [
GoRoute(
path: ':id',
builder: (context, state) {
final id = state.pathParameters['id']!;
return PromoDetailScreen(id);
},
),
],
),
],
),
],
);
Now a deep link to yourapp://app/promo/123 results in the stack:
HomeScreen → ListPromoScreen → PromoDetailScreen