How to use PageView widget in Flutter

The PageView widget in Flutter allows us to create a scrollable list of pages that users can swipe through horizontally. It's commonly used to implement features such as onboarding screens, image galleries, and slideshows.

Constructor and parameters

The PageView widget provides a constructor with various parameters to customize its behavior and layout.

PageView({
  Key? key,
  Axis scrollDirection = Axis.horizontal,
  bool reverse = false,
  PageController? controller,
  ScrollPhysics? physics,
  bool pageSnapping = true,
  ValueChanged<int>? onPageChanged,
  List<Widget> children = const <Widget>[],
  DragStartBehavior dragStartBehavior = DragStartBehavior.start,
  bool allowImplicitScrolling = false,
  String? restorationId,
  Clip clipBehavior = Clip.hardEdge,
  ScrollBehavior? scrollBehavior,
  bool padEnds = true
})

Let's take a closer look at each parameter and its purpose:

  • key: An optional key that uniquely identifies this widget.

  • scrollDirection: The axis along which the pages scroll (default is horizontal).

  • reverse: Whether to reverse the scroll direction (e.g., right-to-left).

  • controller: A controller for interacting with the PageView.

  • physics: Custom physics for the scroll behavior.

  • pageSnapping: Whether to snap to the nearest page when scrolling ends.

  • onPageChanged: A callback that is invoked when the page changes.

  • children: The list of widgets representing individual pages.

  • dragStartBehavior: Determines the starting point of the drag behavior.

  • allowImplicitScrolling: Whether implicit scrolling is allowed.

  • restorationId: An optional ID used to save and restore the scroll position.

  • clipBehavior: How to clip content overflowing the PageView.

  • scrollBehavior: Custom scroll behavior.

  • padEnds: Whether to add padding at the ends to prevent edge effects.

Importing necessary libraries

Before using the PageView widget, make sure to import the required libraries in our Dart file:

import 'package:flutter/material.dart';

Variable declaration

The PageController is a class provided by Flutter that allows us to control the PageView. We can use this controller to programmatically change the displayed page, jump to a specific page, and more.

final PageController controller = PageController();

Creating a list of widgets

We'll begin by creating a list of widgets separately, which we'll later pass into the PageView. This allows us to manage the pages more efficiently.

final List<Widget> pages = [
Center(
child: Text(
'First Page',
style: TextStyle(fontSize: 22),
),
),
Center(
child: Text(
'Second Page',
style: TextStyle(fontSize: 22),
),
),
Center(
child: Text(
'Third Page',
style: TextStyle(fontSize: 22),
),
),
];

Basic PageView example

The PageView widget is the heart of this code snippet. In the below code, it displays the basic syntax of the PageView.

PageView(
controller: controller,
children: pages,
);
  • Line 2: The controller is an instance of PageController. It allows us to control the PageView, like programmatically changing the displayed page or getting the current page index.

  • Line 3: It takes a list of child widgets, which in this case is the pages list containing instances of the Center widget wrapping Text widgets.

Customizing the PageView behavior

By default, the PageView scrolls horizontally. If you want to change the scrolling direction to vertical or enable reverse scrolling, you can use the scrollDirection and reverse properties.

PageView(
controller: controller,
scrollDirection: Axis.vertical, // Set the scrolling direction to vertical
reverse: true, // Enable reverse scrolling
children: pages,
);

Code example

We get the following output by putting together the code explained above.

import 'package:flutter/material.dart';

void main() => runApp( PageViewExampleApp());

class PageViewExampleApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Educative PageView Answer')),
        body:  PageViewExample(),
      ),
    );
  }
}

class PageViewExample extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    final List<Widget> pages = [
      Center(
        child: Text(
          'First Page',
          style: TextStyle(fontSize: 22), 
        ),
      ),
      Center(
        child: Text(
          'Second Page',
          style: TextStyle(fontSize: 22), 
        ),
      ),
      Center(
        child: Text(
          'Third Page',
          style: TextStyle(fontSize: 22), 
        ),
      ),
    ];

    final PageController controller = PageController();

    return PageView(
      controller: controller,
      children: pages,
    );
  }
}

Conclusion

The PageView widget in Flutter provides a powerful and versatile tool for creating scrollable lists of pages. With its various parameters, such as the scrollDirection and reverse, we can customize the scrolling behavior to fit different use cases. By using a list of widgets and a PageController, we can easily manage and control the content displayed in the PageView. This flexibility allows us to create engaging user experiences like onboarding screens, image galleries, and more.

Copyright ©2024 Educative, Inc. All rights reserved