Scenario:
- User is swiping through the PageView widgets
- User arrives to the last widget
- Instead of forcing the user to tap on button, we want user to continue swiping in order to swipe from last widget and load the next screen
Initial setup:
1 2 3 4 5 6 7 8 9 |
PageView.builder( itemBuilder: (context, index) => Container( color: Colors.cyan, margin: const EdgeInsets.all(10), child: Center( child: Text(slides[index]), )), itemCount: slides.length, ) |
For full example checkout: github.com/dribtech/flutter_swipe_past_last_page/blob/eaba683bd337aca9211eb3c172d1cd831605d2ff/lib/main.dart
Solution:
Wrap PageView with NotificationListener<OverscrollNotification> in order to catch the over-scroll event and load the next screen:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
NotificationListener<OverscrollNotification>( onNotification: (OverscrollNotification overscrollNotification) { if(overscrollNotification.overscroll < 10) { return false; } Navigator.pushNamed(context, '/second'); return true; }, child: PageView.builder( itemBuilder: (context, index) => Container( color: Colors.cyan, margin: const EdgeInsets.all(10), child: Center( child: Text(slides[index]), )), itemCount: slides.length, ), ), ), |
The
10 in the
if(overscrollNotification.overscroll < 10) { is the “amount” of over-scroll that must be reached before we load the next screen. Without it accidental taps would
trigger loading of the next screen. Experiment which number works best for you.
For full example checkout github.com/dribtech/flutter_swipe_past_last_page/blob/master/lib/main.dart
Or visit: github.com/dribtech/flutter_swipe_past_last_page
Other popular solutions
GestureDetector & NeverScrollableScrollPhysics
Wrap the PageView with GestureDetector and add physics: NeverScrollableScrollPhysics() in PageView .
Pros: reacts on “drag” no need to guess amount of over-scroll. We must implement scrolling between PageView widgets.
Cons: also overrides default look and feel when swiping between PageView widgets. And this was a deal breaker for me.
NotificationListener<OverscrollIndicatorNotification>
Wrap PageView with NotificationListener<OverscrollIndicatorNotification>and implement onNotification
Cons: reacts on the slightest tap instead of clear drag
Cool post! Very helpful indeed.
or others who might run into it:
On Flutter 3.7.3 I could not get the overscroll notification to fire on iOS (I only tried the emulator) and it might be because of this very long standing issue: https://github.com/flutter/flutter/issues/17649
Hi,
Unfortunately I don’t have access to ios development tools – so I can’t check it by my self.
Thank you for the link!