Member-only story
Flutter PageView Widget
A simple way to swipe between screens
This article was updated for Flutter 3.3 on January 9, 2023.
If you haven’t already seen the Flutter Widget of the Week video about PageView
, watch that first. The rest of this article is based on it.
The video showed you the essence of what PageView
does. This article will fill out the code for you to play with. Scroll down to the end to get the full code demo, or just open this project on DartPad.
The basics
A PageView
allows the user to swipe between different screens in your app. All you need to set it up are a PageViewController
and a PageView
.
PageViewController
Put the PageViewController
inside the State
of a StatefulWidet
and initialize it inline or in the initState()
method.
final _controller = PageController(
initialPage: 0,
);
Here it’s initialized inline. The initialPage
parameter set to 0
means that the first widget child of the PageView
will be shown first (since it’s a zero-based index).
Then dispose the controller in the State’s onDispose()
method:
@override
void dispose() {
_controller.dispose();
super.dispose();
}
PageView
After that all you have to do is set the controller
on the PageView
and give it some children
that you want to swipe between.
PageView(
controller: _controller,
children: const [
MyPage1Widget(),
MyPage2Widget(),
MyPage3Widget(),
],
)
Here’s what that looks like:
And here is that code code in context:
class PageViewDemo extends StatefulWidget {
const PageViewDemo({super.key}); @override…