You may have used WillPopScope earlier to detect the page close in Flutter, this widget is now deprecated by the Flutter team and will be replaced by a better widget called PopScope.
The older method of detecting the page close was like
WillPopScope(
onWillPop: () async {
// your logic
return false;
},
)
In specific instances, you might need to have more control over the PopScope which leads to this new component creation.
Let’s say you wanted to show a dialog to show when the contents of the page change when a user tries to close the screen, this should work. But if the user didn’t make any changes we have to write unnecessary logic to avoid showing the dialog and close without it.
In the new PopScope widget, this is pretty straightforward. Here is how you can do it.
/// NEW CODE
PopScope(
canPop: true,
onPopInvoked : (didPop){
// logic
},
)
In this new code, you could just pass in a boolean to enable or disable the PopLogic. If no changes were made, you could pass false to the canPop argument and the page closes as usual. But when any changes are made, you could pass true which runs the logic under onPopInvoked which is pretty modular and better than the previous WillPopScope.
The reason for making a completely new widget instead of updating WillPopScope I think was to save old code from breaking and it’s pretty easy to change the code with the new widget.
This also carries a few disadvantages over the original WillPopScope, Sometimes, a page might want to prevent pops from multiple places. This was trivial since if any of the onWillPop callbacks returned false, the pop would be prevented. This was especially useful for, for instance, displaying a loading overlay and having it register pop-prevention callbacks.
With PopScope
and PopEntry
the same behaviour is quite more difficult to achieve and will no longer work out of the box, since now ALL the PopScope
s and their callbacks will need to be synchronized to ensure there aren’t duplicate pops going on by the callbacks.
But I guess the reason for this change is for the new Android predictive back. The Flutter app needs to preemptively tell the Android activity if it can pop before the pop is called.
So like it or not, the Flutter team took the step and deprecated the component and we have to live with it. If you have any issues, feel free to comment down below.