Roger Villamarin
Roger Villamarin

Reputation: 231

How to move backward in PageView when press back button [Flutter]

I want to move backward when press the back button using a pageView, I read about the WillPopScope component, but I am not pushing/poping another screens. I am just moving in diferent pages on the pageView.

Any clue how to do that?

Best regards.

Upvotes: 6

Views: 8463

Answers (3)

Smily
Smily

Reputation: 3080

Yep, you can achieve so using WillPopScope. Not sure if this is optimal though, but it works perfectly with me; keep in mind that I wanted the back button to work from the one of the pages to the one before it, and not over all pages, but I am sure the solution applies.

In the page, I surrounded everything with WillPopScope like this

return new WillPopScope(
  onWillPop: () => Future.sync(onWillPop),
  child: // Whatever your page was

Now, you will have to define the proc onWillPop, and it is like this in my case

bool onWillPop() {
  _controller.previousPage(
    duration: Duration(milliseconds: 200),
    curve: Curves.linear,
  );
  return false;
}

In my case, this never fails as it is only used in one of the views, and only one.

In your case, you may wanna condition like this:

bool onWillPop() {
  if (_controller.page.round() == _controller.initialPage)
    return true;
  else {
    _controller.previousPage(
      duration: Duration(milliseconds: 200),
      curve: Curves.linear,
    );
    return false;
  }
}

Hope this helps. For reference on overriding the back button in general, refer to this other StackOverFlowAnswer.

EDIT: Added a return value to my onWillPop to remove dart warning.

Upvotes: 12

geegog
geegog

Reputation: 103

You can also write the onWillPop() like this:

if (_controller.page.round() == _controller.initialPage) {
      return true;
    } else {
      _controller.previousPage(
        duration: Duration(milliseconds: 200),
        curve: Curves.linear,
      );
      return false;
    }

So it always return a bool.

Upvotes: -1

braulio.cassule
braulio.cassule

Reputation: 1449

You can use PageController to control your PageView.

    PageController _pageController;

You can use the PageController got to the previous page:

    _pageController.previousPage(duration: Duration(milliseconds: 300), curve: Curves.linear);

Or to go to the initial page:

     _pageController.jumpToPage(_pageController.initialPage);

Upvotes: 1

Related Questions