In Flutter, to programmatically trigger the behavior of the back button (e.g. Android’s system back) and go through a PopScope, you can use the Navigator.pop(context) method in combination with how PopScope (formerly WillPopScope) handles the back navigation.
✅ Solution
To simulate a back press and ensure it goes through PopScope’s onPopInvoked:
PopScope(
canPop: true, // or false if you want to manually decide
onPopInvoked: (didPop) {
// handle what happens when a pop is triggered
if (didPop) {
print("Popped via back button or Navigator.pop");
} else {
print("Pop attempt denied");
}
},
child: Scaffold(
appBar: AppBar(
title: Text('Demo'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
// This will trigger the PopScope logic
Navigator.of(context).maybePop();
},
child: Text('Simulate Back Press'),
),
),
),
)
✅ Why use maybePop() instead of pop()?
Navigator.pop(context)always pops the current route.Navigator.maybePop(context)checks with anyPopScope(orWillPopScope) and only pops if allowed.maybePop()will trigger the logic inside youronPopInvoked.
✅ Summary
- Use
Navigator.maybePop(context)to simulate a back press. - Wrap your screen in a
PopScopeand useonPopInvokedto catch and handle the event. - Set
canPop: trueorfalseto control behavior dynamically.
