Know which Route was removed in onPopPage on Navigation 2.0 in Flutter

341

You can give your page a name:

MaterialPage(
    key: ValueKey(viewModel.otherUserIDForChat),
    name: viewModel.otherUserIDForChat,
    child: SingleChatScreen( ... ),
),

then in opPopPage you can check for the name:

onPopPage: (route, result) {
   if (!route.didPop(result)) return false;

   if (route.settings.name == viewModel.otherUserIDForChat) {
       // do your thing
   }

   return true;
}
Share:
341
Andrey Solera
Author by

Andrey Solera

Passionate about programming! “When you don't create things, you become defined by your tastes rather than ability. your tastes only narrow & exclude people. so create.” ― Why The Lucky Stiff

Updated on December 28, 2022

Comments

  • Andrey Solera
    Andrey Solera over 1 year

    I want to know which Page was being removed by the navigation in Flutter (I'm using Navigation 2.0). I have the following code:

    @override
      Widget build(BuildContext context) {
        return Navigator(
          key: this.navigatorKey,
          onPopPage: (route, result) {
            if (!route.didPop(result)) return false;
    
            // TODO check for the page that was poped
            viewModel.otherUserIDForChat = null;
    
            return true;
          },
          pages: _generatePages(),
        );
      }
    

    As seen in the previous code I'm setting to null the otherUserIDForChat, however, I would like to know if the page that was poped was the chat screen that I've implemented inside the _generatePages, here's the code for that:

    /// Function that aggregates pages depending on [AppViewModel]'s values
      List<Page> _generatePages() {
        List<Page> pages = [];
    
        pages.add(
          MaterialPage(
            child: HomeScreen(),
          ),
        );
    
        if (viewModel.otherUserIDForChat != null) {
          pages.add(
            MaterialPage(
              key: ValueKey(viewModel.otherUserIDForChat),
              child: SingleChatScreen(
                parameters: SingleChatScreenParameters(
                  otherUserID: viewModel.otherUserIDForChat,
                ),
              ),
            ),
          );
        }
    
        return pages;
      }
    

    How can I know which page was being poped?

    • Tanha Patel
      Tanha Patel about 3 years
      whatever the page is displayed will be popped out of the stack as it removes the page which is on top.
    • Andrey Solera
      Andrey Solera about 3 years
      yes, but I have multiple pages and I want to react differently when each screen is being poped, how can I know the exact page that was poped out?
    • Tanha Patel
      Tanha Patel about 3 years
      In that case you can take reverse approach that if you want to navigate to screen A then while navigating pop desired screen and so on. As the Navigatore.pop() simply pops out the top most screen.