How do I set the initial page of PageView in Flutter?
You need to set initial page like,
PageController _controller = PageController(initialPage: 3);
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();
}
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,
)
)
),
);
}
}