Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 692
Roger Villamarin Avatar asked Jul 24 '18 21:07

Roger Villamarin


2 Answers

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.

like image 57
Smily Avatar answered Sep 29 '22 08:09

Smily


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);
like image 35
braulio.cassule Avatar answered Sep 29 '22 10:09

braulio.cassule