Skip to content
DeveloperMemos

Migrating from WillPopScope to PopScope in Flutter

Flutter, PopScope, Navigation1 min read

The world of Flutter development is constantly evolving, and sometimes things get deprecated. One such case is the WillPopScope widget, which was used to control the back button behavior in your app. With the introduction of Android 14's Predictive Back Gesture, WillPopScope is no longer sufficient. Thankfully, Flutter offers a new and improved alternative: PopScope.

This article will guide you through the migration process, explaining the key differences between the two widgets and how to seamlessly update your code.

Why the Change?

The core reason for the shift is the new Predictive Back Gesture in Android 14. This feature anticipates the user's back button press and initiates the animation immediately. With WillPopScope, which was asynchronous, there wasn't enough time for the app to decide whether the pop should be allowed. PopScope addresses this by requiring a synchronous decision upfront.

The Migration Process

Migrating to PopScope is a straightforward process. Here's a breakdown of the key steps:

  1. Replace WillPopScope: The first step is to swap out all instances of WillPopScope in your code with PopScope.

  2. Understand canPop: PopScope introduces the canPop parameter, which is a boolean value. Set it to true to allow back navigation and false to disable it. In many cases, logic from your old onWillPop callback can be moved to setting canPop at build time.

  3. Use onPopInvoked (Optional): If you still need to be notified when a pop attempt occurs, use the onPopInvoked callback. This is similar to onWillPop, but keep in mind it's called after the pop is handled, not before.

Here's an example of a basic migration:

1// Using WillPopScope
2WillPopScope(
3 onWillPop: () => _onWillPop(),
4 child: MyWidget(),
5);
6
7// Using PopScope
8PopScope(
9 canPop: canPopValue, // Set based on your logic
10 onPopInvoked: (didPop) {
11 if (didPop) {
12 // Handle pop attempt
13 }
14 },
15 child: MyWidget(),
16);

Additional Considerations

For more complex scenarios, you might need to adjust your logic slightly. Refer to the official Flutter documentation on Android Predictive Back Navigation for in-depth explanations and troubleshooting tips.

By migrating to PopScope, you ensure your app remains compatible with the latest Android features and provides a smooth back navigation experience for your users.