1

I have a simple PageView widget that controls navigation between two screens/views

final PageController _pageController = PageController(
  initialPage: 0,
);

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


PageView(
  controller: _pageController,
  children: [
      firstScreen(),
      secondScreen(),
  ],
);

Right now the user is able to swipe on any part of the screen just a little bit and the view changes.

Is there a way to somehow restrict the user to be able to swipe for example only from the edges using PageView?

jonneroni
  • 11
  • 2

1 Answers1

1

You can disable the PageView to scroll and wrap it in a GestureDetector, use it's onPanUpdate method to make the scrollController change its index. Something like this,

int pageViewIndex = 0;

GestureDetector(
    onPanUpdate: (details) {
        Offset position = details.localPosition;
        int xPosition = position.dx;

        // USE THIS xPosition TO VALIDATE YOUR DESIRED xPosition
        if (!isValidXPosition) return;

        // Swiping in right direction.
        if (details.delta.dx > 0 && pageViewIndex < pagesLength - 1) {
            setState(() {
                 pageViewIndex = pageViewIndex + 1;
            });
            _pageController.animateToPage(pageViewIndex);
        }
        // Swiping in left direction.
        if (details.delta.dx < 0 && pageViewIndex > 0) {
            setState(() {
                 pageViewIndex = pageViewIndex - 1;
            });
            _pageController.animateToPage(pageViewIndex);
        }
    },
    child: PageView(
        physics: NeverScrollableScrollPhysics(),
        controller: _pageController,
        children: [
            firstScreen(),
            secondScreen(),
        ],
    ),
)

Hope that's helpful. Comment if more help is needed..