Search code examples
androidiosflutternavigation

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


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?


Solution

  • 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;
    }