在 Flutter 的 Navigation 2.0 上的 onPopPage 中知道哪条 Route 被移除了

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

我想知道 Flutter 中的导航正在删除哪个页面(我使用的是导航 2.0)。 我有以下代码:

@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(),
    );
  }

如前代码所示,我将 otherUserIDForChat 设置为 null,但是,我想知道弹出的页面是否是我在 [=] 中实现的聊天屏幕13=],这是它的代码:

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

我如何知道正在弹出哪个页面?

你可以给你的页面一个 name:

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

然后在 opPopPage 中您可以检查名称:

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

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

   return true;
}