Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend PageView to both sides with builder?

Tags:

flutter

dart

Using PageView.builder I can get an infinite list of pages, but only in one direction, i.e. it is finite in the other direction!

The default scrollDirection of a PageView is Axis.horizontal. So what I mean is that in the regular case I can only scroll infinitely to the right, but not to the left.

illustration

I want to be able to scroll infinitely in both directions. I have not found a way to do this, especially, because I would expect the itemBuilder to give out negative indices then, which I have never seen. That leads me to wondering whether this is implemented at all, but I am open to custom solutions and will try to come up with something aswell.

like image 673
creativecreatorormaybenot Avatar asked May 13 '18 22:05

creativecreatorormaybenot


2 Answers

I solved it pretty straight forward. Honestly, I must have been out of my mind writing the question and issueing the bounty.

// number is irrelevant
final initialPage = (
    .161251195141521521142025 // :)
    * 1e6,).round();
final itemCount = getSomeItemCount();

PageView.builder(
  pageController: PageController(
    initialPage: initialPage,
  ),
  itemBuilder: (context, page) {
    final index = itemCount - (initialPage - page - 1) % itemCount - 1;
    return getPageContent(index);
  },
);

I am not sure if I should give credit to Rémi Rousselet because I was using this method before he proposed his answer. I just wanted to mention him because this question is getting undeserved traffic and he helped me to solve my problem :)

like image 35
creativecreatorormaybenot Avatar answered Oct 03 '22 12:10

creativecreatorormaybenot


There's no official way of having an infinite scroll in both directions.

But you can instead use PageController's initialPage property. Setting it to an absurdly big value. And then use this value as your "index 0".

class MyHomePage extends StatelessWidget {
  final PageController pageController = new PageController(initialPage: 4242);

  @override
  Widget build(BuildContext context) {
    return new Scaffold(body: new PageView.builder(
      controller: pageController,
      itemBuilder: (context, _index) {
        final index =  _index - 4242;
        return new Container(
          margin: const EdgeInsets.all(9.0),
          color: Colors.red,
          child: new Center(
            child: new Text(index.toString()),
          ),
        );
      },
    ));
  }
}
like image 160
Rémi Rousselet Avatar answered Oct 03 '22 10:10

Rémi Rousselet