Bidev
IntermediateNavigation & Routing

How do you intercept the back button in Flutter?

Short Answer

Wrap the screen in a PopScope widget (the modern replacement for the deprecated WillPopScope), setting canPop to false and handling the back attempt in the pop callback — commonly used for an 'unsaved changes' confirmation dialog.

WillPopScope's onWillPop callback returned a Future<bool> deciding whether the pop should proceed — but it was deprecated because it didn't compose well with Navigator 2.0's declarative model and predictive back gestures on Android. PopScope replaces it: set canPop: false to prevent the default pop, and inspect the pop attempt in its callback, from which you can show a confirmation dialog and call Navigator.pop() manually if the user confirms.

Code Example

PopScope(
  canPop: false,
  onPopInvokedWithResult: (didPop, result) async {
    if (didPop) return;
    final shouldPop = await showConfirmDialog(context);
    if (shouldPop && context.mounted) Navigator.pop(context);
  },
  child: const EditScreen(),
)

Common Mistakes

  • ×Still using the deprecated WillPopScope in new code instead of PopScope.
  • ×Setting canPop: false without ever actually popping programmatically afterward, permanently trapping the user on the screen.