Flutter › Navigation & Routing in Flutter
How can you properly intercept and correctly handle the physical Android back button using the PopScope widget, such as showing a confirmation dialog before genuinely actually allowing the user to leave a screen with unsaved changes?
IntermediateAnswer
PopScope, which properly replaced the earlier deprecated WillPopScope widget, lets you properly intercept an attempted pop operation, whether triggered by the physical Android back button, a swipe gesture on iOS, or a direct programmatic call, and its own canPop property together with the onPopInvoked callback let you conditionally prevent that particular pop from actually genuinely happening, such as showing a confirmation dialog asking the user to confirm discarding any unsaved changes before actually genuinely allowing them to actually properly leave that particular screen.
PopScope(
canPop: !hasUnsavedChanges,
onPopInvoked: (didPop) {
if (!didPop) showDiscardChangesDialog();
},
child: EditScreen(),
)Real-world example A document editing screen uses PopScope to properly show a confirmation dialog asking whether the user genuinely wants to discard their own unsaved changes whenever they attempt to navigate away using the physical Android back button.