DeKekem
DeKekem

Reputation: 1743

Remove routes from stack using Navigator flutter

I have been asking myself which navigation style should I stick with for my app: Navigator, named routes, go_router are my choices. My app is not that complex and I don't need deep linking. But I need to open some screen from notification. For now I use Navigator.push/pop.

I have read about named routes but I don't like the way arguments are passed. It is too complicated compared to Navigator, at least for me.

My only problem with Navigator is that I could not find out how to pop some routes until I reach a specific one.

Here my use case:

User enter screen A and follow some process until screen C. On screen C they can then click DONE and should be redirected by to Screen A. They can of course go the history backward, C -> B -> A with the back button if they want to correct some data.

Screen A -> Screen B -> Screen C

For now I use Navigator.of(context).pop(); Navigator.of(context).pop();, so twice. I have tried Navigator.of(context).popUntil((route) => route.isFirst); but it takes the user back pass Screen A. Screen A is not the bottom-most active route on the navigator.

Upvotes: 0

Views: 64

Answers (1)

Jesse Hayward
Jesse Hayward

Reputation: 148

So there a few options, but to keep code clean and explicit, I use namedRoutes, you can write some good handlers for taking arguments as a map rather than directly passing, however it means you have context if you do choose to go the Navigator route of manual handling with things like:

navigatorKey.popUntil((route) => route.settings.name == TopNavigationScreen.id);

This will give you what you need in returning from your position in the stack until a particular page.

My typical setup is to have a static id on each "page" so in setup I can just call that as the name of each route:

routes: {
    StartScreen.id: (context) => const StartScreen()
}

to be called later with :

Navigator.pushNamed(StartScreen.id);

Now if you want arguments use the following:

It's essentially the same, the setup just needs to know how to get each argument for your "page":

 Map getSettingMap(context) => ModalRoute.of(context)!.settings.arguments as Map;

routes:{
     ChatScreen.id: (context) => ChatScreen(
          interactionId: getSettingMap(context)["interaction_id"],
          userId: getSettingMap(context)["user_id"]
}

And to push that route with arguments

navigatorKey.pushNamed(ChatScreen.id, arguments: {
    "interaction_id": interaction,
    "user_id": currentUser.id,
  });

Upvotes: 0

Related Questions