Is there a way to have an infinite loop using PageView in Flutter? For example if my PageView has 5 pages, after swiping to page 5, I would be able to swipe again in the same direction to get to Page 1.
Sign in to your account Currently in PageView there is no way using infinite loop. For example, my PageView has 3 pages, after swiping to the page 3 I would be able to swipe again in the same direction to get to page 1. And if I'm on the page 1, I would be able to get to the page 3 by swiping to the left.
The PageView widget allows the user to transition between different screens in their flutter application. All you need to set it up are a PageViewController and a PageView. scrollDirection: It sets the axis of scrolling ( Vertical or horizontal ).
Now we can use a PageController and control the visibility of pages. It means, which page is visible in the view is controlled by PageController. It has other powers as well, and we’ll discuss that in detail in the next article that covers PageView.builder constructor. To sum up, a PageView widget generates scrollable pages on the screen.
It's not really infinite, but most users will not scroll 10000 pages back, so it works for my use case. As far as I know, there isn't an elegant way to make it truly infinite. You could probably set up a listener so that whenever the controller.page is about to become 0, you set it back to 10000 * pageCount or something similar.
By default, PageView.builder
is infinite in flutter. Unless you provide an itemCount
.
The following will print page from 0 to 4 infinitely
final controller = new PageController(initialPage: 999);
...
new PageView.builder(
controller: controller,
itemBuilder: (context, index) {
return new Center(
child: new Text('${index % 5}'),
);
},
)
If you have a list of pre-defined Widgets, you can achieve continuous scrolling using:
return PageView.builder(
itemBuilder: (context, index) {
return _children[index % _children.length];
},
controller: pageController,
);
You can achieve infinite scrolling using PageView builder, without giving value to itemCount there will be infinite pages, you just have to maintain the page index which will be painted on screen.
PageView.builder(
controller: _pageController,
scrollDirection: Axis.horizontal,
onPageChanged: (index) {
setState(() {
_currentIndex = index % _walkthroughSlides.length;
});
},
itemBuilder: (context, index) {
return _walkthroughSlides[index % _walkthroughSlides.length];
},
)
I've found a good solution using this lib https://pub.dev/packages/infinity_page_view
Just import the lib and use InfinityPageView
instead of PageView
InfinityPageView(
controller: infinityPageController,
itemCount: colorList.length,
itemBuilder: (context, index) {
return Container(
color: colorList[index];
);
},
)
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