Flutter PageView Tutorial

Flutter PageView Example – How To Use Build Scrollable PageView.

PageView is a widget that creates a scrollable view that work page by page.PageView, for example, is famously used in Tinder UI which swipes to accept or reject. Here in the tutorial, we will learn how to use PageView.

PageView widget is a class in the material library of flutter SDK. It displays its children one after another that scrollable.

PageController is class used to control the behaviour of PageView like say we want to move from index 1 to directly 4 and this can be done with PageController.Normally you would have swipe 3 times to get to 4th view on PageView.

Tutorial

Step 1:

Setup a project by using Android Studio or Visual Studio.Remove all generated sample code.Pass in HomeView() in home parameter of MaterialApp widget.

Step 2:

Create a dart file named homeview.dart and write stful in the editor which autocompletes to generate a Stateful widget.

Step 3:

Go to build method and pass the method below.

Widget buildPageView(){
  return PageView(
    scrollDirection: Axis.horizontal,
    controller: controller,
    children: const <Widget>[
      Center(
        child: RaisedButton(
          child: Text("Move to 3rd page"),
          onPressed: onClickMove,
        ),
      ),
      Center(
        child: Text('Flutter Page'),
      ),
      Center(
        child: Text('Love Page'),
      )
    ],
  );
}

scrollDirection:Axis in which you define to like horizontal or vertical.

controller:Takes in PageController instance to bind controller and pageview.

children:Child view which you want to build while we scroll.

All Code:

import 'package:flutter/material.dart';

class HomeView extends StatefulWidget {
  @override
  _HomeViewState createState() => _HomeViewState();
}

class _HomeViewState extends State<HomeView> {

  final PageController controller = PageController(initialPage: 0);

  @override
  Widget build(BuildContext context) {
    return buildPageView();
  }

  Widget buildPageView(){
    return PageView(
      scrollDirection: Axis.horizontal,
      controller: controller,
      children: const <Widget>[
        Center(
          child: RaisedButton(
            child: Text("Move to 3rd page"),
            onPressed: onClickMove,
          ),
        ),
        Center(
          child: Text('Flutter Page'),
        ),
        Center(
          child: Text('Love Page'),
        )
      ],
    );
  }

  void  onClickMove(){
    controller.jumpToPage(2);
  }


}