Flutter: How to get a pop value when the original target page has been replaced?

Issue

Let’s say I have three pages, A, B and C.

From page A I have a FloatingActionButton to navigate to page B with a then() statement for the return value. If the return value equals false nothing happens, in any other case page A will be refreshed:

FloatingActionButton(
  onPressed: () {
    Navigator.of(context).pushNamed(B.routeName).then((value){
      if (value != false){
        _refresh(); // My own function to refresh page A
      }
    });
  },
  ...
)

In page B, I have a Scaffold with just a background screen and a FloatingButton. The button leads to page C, while clicking on the screen will lead back to page A, without refresh necessary.

Scaffold(
  body: GestureDetector(
    onTap: () {
      Navigator.of(context).pop(false);
    },
    ...
  ),
  FloatingActionButton(
    onPressed: () {
      Navigator.of(context).pushReplacementNamed(C.routeName);
    },
    ...
  ),
)

My problem is that when I click the floating action button to go to page C, page B pops, and page A gets null value in its then() statement.

How do I avoid page B popping, and ‘link’ the return value in the then() statement from page A to the value of pop() statement from page C instead of B?

The real problem here is that page A will not refresh when I pop page C, as its then() has already triggered by page B, not the fact that it refreshed when page B pops.

Solution

in page B instead of pushReplacementNamed you can just push and await for result in page c then when it returned value you can pop to page A,
in page B you can write:

  onPressed: () {
Navigator.of(context).pushNamed(C.routeName).then((value){
  Navigator.of(context).pop(false);
});

},

Answered By – Bunny1376

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.