17

I have an app that use PageView and I want to make it responsive – such that on a tablet, it shows 3 pages and with a smartphone, it shows only one:

enter image description here

How can I change the number of pages shown in a PageView?

4 Answers 4

29

You can control how many pages are displayed in a PageView through a PageController

var controller = PageController(viewportFraction: 1 / 3);

Then pass it to your PageView:

PageView(
  controller: controller,
  ...
), 
1
  • 4
    This seems to only work well with viewport 1/3 but not with 1/2 because it shows one page in the center and half a page to the left and another half to the right. Is there a way to show 2 whole pages next to each other?
    – Jonas
    Commented Aug 15, 2020 at 15:57
4

You have to use LayoutBuilder to check the max width and then you can set the PageController(viewportFraction: ); accordingly.

Here is an example:

  PageController pageController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: LayoutBuilder(builder: (context, constrains) {
        if (constrains.maxWidth < 600) {
          pageController = PageController(viewportFraction: 1.0);
        } else {
          pageController = PageController(viewportFraction: 0.3);
        }
        return PageView.builder(
          controller: pageController,
          itemCount: places.length,
          itemBuilder: (context, index) {
            // return your view for pageview
          },
        );
      }),
    );
  }
1
PageView.builder(
        controller: PageController(
          viewportFraction: 0.8,
        ),
        padEnds: false,
        itemCount: ...,
        itemBuilder: (context, index) {
          return ...;
        },
      );

is worked for me

0
0

Some addition to accepted answer: if you wand to display two or other even number of pages use padEnds: false

          PageView.builder(
            controller: PageController(
              viewportFraction: 1/2,
            ),
            padEnds: false,
            itemCount: ...,
            itemBuilder: (context, index) {
              return ...;
            },
          );

Not the answer you're looking for? Browse other questions tagged or ask your own question.