How to scroll or jump to position of PageView.builder or PageController in Flutter?

jazzbpn picture jazzbpn · May 9, 2019 · Viewed 17.5k times · Source

Issue: Unable to scroll to POSITION after loading the Pageviews using PageController *

like ViewPager scroll to specific page in Android

Widget _buildCarousel(BuildContext context, int selectedIndex) {

    PageController controller = PageController(viewportFraction: 1, keepPage: true);
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        SizedBox(
          // you may want to use an aspect ratio here for tablet support
          height: 400.0,
          width: 240,
          child: PageView.builder(
            itemCount: assetImageList.length,
            controller: controller,
            itemBuilder: (BuildContext context, int itemIndex) {
              return _buildCarouselItem(context, selectedIndex, itemIndex);
            },
          ),
        )
      ],
    );
  }

Answer

jazzbpn picture jazzbpn · May 9, 2019

Finally found the answer. Just set the initialPage: mSelectedPosition attribute like:

child: PageView.builder(
        itemCount: mTemplateModelList.length,
        controller: PageController(initialPage: mSelectedPosition, keepPage: true, viewportFraction: 1),
        itemBuilder: (BuildContext context, int itemIndex) {
          return _buildCarouselItem(context, selectedIndex, itemIndex);
        },
      ),

OR if you want to scroll the page after the button is clicked then, you can use jumpTo() method using PageController which is clearly mentioned below by another user: @android.