Flutter pageview disable swipe

Flutter PageView Disable Swipe

To disable swipe functionality in Flutter’s PageView widget, you can make use of two properties: physics and onPageChanged.

1. Using physics property:

To disable swipe, set the physics property of PageView to NeverScrollableScrollPhysics(). This physics object does not allow the PageView to be scrolled or swiped.


    PageView(
      physics: NeverScrollableScrollPhysics(),
      ...
    )
  

2. Using onPageChanged property:

The onPageChanged property allows you to handle the page change event in the PageView. By keeping track of the current page index, you can prevent the swipe action by explicitly setting the PageController to the current page whenever a swipe is attempted.


    PageController _pageController = PageController(initialPage: 0);
    int _currentPage = 0;
    
    PageView(
      controller: _pageController,
      onPageChanged: (int page) {
        if (page != _currentPage) {
          _pageController.jumpToPage(_currentPage);
        }
      },
      ...
    )
  

Example:

Here’s an example that demonstrates the disabling of swipe functionality:


    import 'package:flutter/material.dart';

    void main() {
      runApp(MyApp());
    }

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('PageView Disable Swipe'),
            ),
            body: PageView(
              physics: NeverScrollableScrollPhysics(),
              children: [
                Container(
                  color: Colors.blue,
                  child: Center(child: Text('Page 1')),
                ),
                Container(
                  color: Colors.green,
                  child: Center(child: Text('Page 2')),
                ),
                Container(
                  color: Colors.orange,
                  child: Center(child: Text('Page 3')),
                ),
              ],
            ),
          ),
        );
      }
    }
  

In the above example, the PageView widget has the physics property set to NeverScrollableScrollPhysics(), which disables the swipe functionality. It contains three containers representing different pages with different background colors.

Leave a comment