Search code examples
flutterpageviewsflutter-pageview

Index scrolling problem with PageView.Builder()


i´m trying to make a horizontal scrollable widget. it must be infinit (or kind of), so I´ve done this.

Widget build(BuildContext context) {
    final int initialPage = 1000;

    return Container(
      margin: const EdgeInsets.all(10.0),
      height: 400,
      child: PageView.builder(
        controller: PageController(
          keepPage: true,
          initialPage: initialPage,
        ),

        itemBuilder: (context, position) {

          print(position);

          return Container(child:Text(position),
          );
        },
        itemCount: null,
      ),
    );
  }

Then i scroll right 3 times and the console shows this:

I/flutter (12616): 1000
I/flutter (12616): 1001
I/flutter (12616): 1002
I/flutter (12616): 1003

but then when i go backwards, i have to scroll 4 times to see some results, but in the middle it doesn´t show anything.

I/flutter (12616): 1000
I/flutter (12616): 1001
I/flutter (12616): 1002
I/flutter (12616): 1003
I/flutter (12616): 999
I/flutter (12616): 1004
I/flutter (12616): 1005

That was 3 times right, 4 times left and 6 to the right again. Why itemBuilder function doesn´t run sometimes?


Solution

  • Well, I think that the reason is because the print() runs when the PageView builder has to build a new page.

    When you go back (or forward), and you go to a page that was already built, the builder don't run again. (Nothing to build)

    The pages 1003 1002 1001 1000 were already created when going back.


    Please read this, from the documentation of PageView.builder constructor

    Creates a scrollable list that works page by page using widgets that are created on demand.

    This constructor is appropriate for page views with a large (or infinite) number of children because the builder is called only for those children that are actually visible.