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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With