Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the initial page of PageView in Flutter?

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.

like image 736
Christian Avatar asked Nov 20 '19 14:11

Christian


People also ask

What is the default scroll direction for PageView?

The axis along which the page view scrolls. Defaults to Axis. horizontal.

What is Page snapping in flutter?

Snapping Page ScrollA plugin that acts similar to a PageView but either snaps to the closest page or scrolls multiple pages and then snaps, based on how fast the user scrolls.


2 Answers

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,
          )
        )
      ),
    );
  }
}
like image 61
Igor Kharakhordin Avatar answered Sep 30 '22 11:09

Igor Kharakhordin


You need to set initial page like,

PageController _controller = PageController(initialPage: 3);
like image 38
Kavin-K Avatar answered Sep 30 '22 10:09

Kavin-K