Search code examples
flutterdartgesturedetectorpageviewsflutter-pageview

Is there any possible way to add a tap on right to go forward and tap on left to go backward like Instagram stories in flutter Pageview?


Expected implementation of the question is similar to Instagram stories. There exists a package called story_view in flutter which does the same but it's not possible to add a Pageview as child as per my understanding. So, any way this can be implemented in flutter ?


Solution

  • You can use a GestureDetector and PageController on your page view to achieve this. Where GestureDetector is used to get the tapped position of the screen and to call the page controller to go forward or backwards depending on that position.

    Wrap PageView(controller: _pageController,...) with GestureDetector and then define onTapDown something like the below:

    
    GestureDetector(
      onTapDown: (TapDownDetails details) {
        final RenderBox box = context.findRenderObject();
        final localOffset = box.globalToLocal(details.globalPosition);
        final x = localOffset.dx;
    
        // if x is less than halfway across the screen and user is not on first page 
        if(x < box.size.width / 2){
          //   _pageController.previousPage(...)
        }else{
          // Assume the user tapped on the other half of the screen and check they are not on the last page
          //  _pageController.nextPage(...)
        }
    
      },
      child: PageView(
        controller: _pageController,
        ...
      )
    )
    

    As you can see I haven't fully implemented a solution but this should be what you want