How to Build an Onboarding Screen using PageView In Flutter


Tools required to follow the article.


Create a new project with the command below


A PageView allows the user to swipe between different screens in your app. All you need to set it up are a PageViewController which is a required property of the PageView. Each or widget to be swiped is wrapped inside a list of Widget as children.

Initializing PageController

Inside the stateful widget create controller variable whose type is of PageViewController and another int variable to hold the current index of the page

PageController _pageController;int currentIndex = 0;
@overridevoid initState() {  super.initState();  _pageController = PageController();}
@overridevoid dispose() {  _pageController.dispose();  super.dispose();}

Building Screens

Update the body of your scaffold with the following code

Adding Indicators

It is common in different application with onboarding screens to see indicators to which screen is currently viewed. The PageView has provision for a function which listen to the change in screen and return the index of the current screen. You will create a custom stateless widget for the indicator, and place it in the view. Create the Indicator widget with the code below outside the MyHomePage

onChangedFunction(int index) {  setState(() {    currentIndex = index;  });}
onPageChanged: onChangedFunction,

Next and Previous Button

Lastly, you can also add a next or previous button to your page. You can do this by accessing the nextPage and previousPage which are both methods built into the PageController and takes two parameter duration which takes the duration for the page to switch, and curve type of transition animation you want to apply while changing. create two static for the duration and the curve after _pageController

static const _kDuration = const Duration(milliseconds: 300);static const _kCurve = Curves.ease;
nextFunction() {  _pageController.nextPage(duration: _kDuration, curve: _kCurve);}previousFunction() {  _pageController.previousPage(duration: _kDuration, curve: _kCurve);}