16
votes

I have a PageView with four pages in it. I want to start on the third page. That means there are two pages available when the user scrolls up and one page when the user scrolls down.

I tried:

home: PageView(
   controller: MyPageController(),
   children: [Page1(), Page2(), Page3(), Page4()],
   scrollDirection: Axis.vertical,
),

With:

class MyPageController extends PageController {
   @override
   int get initialPage => 3;
}

Unfortunately, that doesn't help me.

3
Did you try to call super(initialPage:0) ? It might use something when initializeddanypata

3 Answers

27
votes

PageController constructor has named parameter initialPage. You can use it, just create the controller somewhere outside of build function:

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  PageController controller;

  @override
  void initState() {
    super.initState();
    controller = PageController(initialPage: 3);
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: PageView(
            controller: controller,
            children: [
              for (var i = 0; i < 4; i++)
                Text('test $i')
            ],
            scrollDirection: Axis.vertical,
          )
        )
      ),
    );
  }
}
5
votes

You need set initial page like,

PageController _controller = PageController(initialPage: 3);
2
votes

For me initialization of PageController with initialPage didn't work for a large number of pages. I also noticed that there is scrolling animation which is undesirable if you want to land to desired page directly.

I used following

  PageController _pageViewController = PageController();

  @override
  void initState() {
    super.initState();
  }

  @override
  void didChangeDependencies() {
    
    WidgetsBinding.instance.addPostFrameCallback((_) {

      if (_pageViewController.hasClients)
        _pageViewController.jumpToPage(3);

    });

    super.didChangeDependencies();
  }