subhangi pawar
subhangi pawar

Reputation: 461

How to detect and pass data in previous screen for Swipe-to-Go-Back Gesture in Flutter App Navigation

This works perfectly when the user clicks on the back button in the app bar. In Android devices, when the user performs a swipe-to-go-back gesture from the right edge of the screen, not able to return data in this case.

I tried using PopScope but not able to navigate to previous screen with data to be returned.

I'm looking for a way to handle the swipe-to-go-back gesture in Android so that I can still return data when the user swipes to navigate back.

PopScope(
                canPop: true,
                onPopInvoked: (didPop) {}, // deprecated
                onPopInvokedWithResult: (didPop, result) {
                  Navigator.of(context).pop(true);
                },

Upvotes: 0

Views: 68

Answers (3)

 Engineer
 Engineer

Reputation: 371

Based on the Android-specific swipe behavior, here's the solution for handling both swipe gestures and back button with data. I've faced similar issues.

Here...

  • canPop: false: It's required to handle custom back logic
  • onPopInvoked: Handles both swipe and system back Matching data in both onPopInvoked and back button.
PopScope(
  canPop: false, // It prevents automatic pop behavior
  onPopInvoked: (didPop) async {
    if (didPop) return;
    
    final data = {
      'key': 'value', 
      'status': 'success'
    };
    
    Navigator.of(context).pop(data);
  },
)

That's all you need to handle swipe-back with data return!

Hope it helps you 👍🏻

Upvotes: 0

Kartikeya Gupta
Kartikeya Gupta

Reputation: 11

The swipe-to-go-back gesture on Android behaves differently from the back button, and onPopInvokedWithResult does not trigger when using gestures. To properly return data when swiping back, you can use ModalRoute.of(context)?.settings to detect the back navigation and pass data.

Use WillPopScope Instead WillPopScope to handle both back button and swipe gestures:

     WillPopScope(
  onWillPop: () async {
    Navigator.pop(context, true); // Pass data when swiping back
    return true;
  },
  child: YourScreenWidget(),
);

Upvotes: 0

Nnamani Daniel
Nnamani Daniel

Reputation: 81

Set canPop to false, if it is set to true, the screen pops before calling onpopinvokedWithResulth

Upvotes: 0

Related Questions