How to move backward in PageView when press back button

CodeWithFlutter
2 Min Read

You can move backward in a PageView when the back button is pressed by using a combination of the WillPopScope and PageController widgets in Flutter.

Here’s an example:

class MyPage extends StatefulWidget {
  @override
  _MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  PageController _pageController;

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (_pageController.page > 0) {
          _pageController.previousPage(
            duration: Duration(milliseconds: 200),
            curve: Curves.easeOut,
          );
          return false;
        }
        return true;
      },
      child: Scaffold(
        body: PageView(
          controller: _pageController,
          children: [
            Container(color: Colors.red),
            Container(color: Colors.green),
            Container(color: Colors.blue),
          ],
        ),
      ),
    );
  }
}

In this example, the WillPopScope widget is used to intercept the back button press event and perform a custom action. The custom action consists of checking if the current page of the PageView is greater than 0, and if so, moving to the previous page using the previousPage method of the PageController. If the current page is 0, the back button press is handled by the system as usual.

Note that you need to create a PageController object and dispose of it properly in the initState and dispose methods, respectively, to ensure that it is properly initialized and cleaned up when your widget is created and destroyed.

Share this Article
Leave a comment