Migrating from WillPopScope to PopScope in Flutter

Fahim Ahmed
2 min readFeb 27, 2024

--

To have more control over the back gesture of our device, the WillPopScope widget was introduced. I use “was” because it is deprecated unfortunately after the v3.12.0–1.0.pre release.

Here comes PopScope, directly replacing the WillPopScope widget. Let’s dive into it and understand why it is needed.

Android 14 introduced a new feature called Predictive Back Gesture. In short, the back gesture is now more unpredictable, and it happens immediately when the user interacts with the gesture.

With predictive back, the back animation begins immediately when the user initiates the gesture and before it has been committed. There is no opportunity for the Flutter app to decide whether it’s allowed to happen at that time. It must be known ahead of time.

For this, PopScope is introduced. From Just In Time (WillPopScope) to Ahead Of Time (PopScope) to make sure the safe routing.

WillPopScope was asynchronus, it was only triggered when the user pressed the back gesture. While PopScope is synchronus, we have to make it clear whether a route is possible or not, even before the user’s attempt.

PopScope.

PopScope({
Key? key,
required Widget child,
bool canPop = true,
})

canPop: it is a boolean property. By default, it is true, which means a back gesture can happen. But if it is false (ahead of time), it blocks the routing.

onPopInvoked: a callback function that is triggered every time a back gesture occurs. To perform any action when the back gesture happens, it can be used. onPopInvoked provides a notification whenever a back gesture is attempted, giving a flexibility to handle it even when popping is disabled.

 PopScope(
canPop: false,
onPopInvoked: (bool didPop){
if (kDebugMode) {
print("$didPop");
}
},
),

Every time a back gesture occurs, onPopInvoked is triggered. didPop indicates whether the route is possible or not.

child: required property. Builds the screen UI.

So, that’s all from me. For more information regarding this,

Official Documentation: https://api.flutter.dev/flutter/widgets/PopScope-class.html

Thanks for reading. Happy coding.

--

--

Fahim Ahmed

Software Engineer | Flutter enthusiast, Interest in Machine Learning and Artificial Intelligence.