How to extend PageView to both sides with builder?

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 :)


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()),
          ),
        );
      },
    ));
  }
}

Tags:

Dart

Flutter