Search code examples
flutterflutter-webflutter-pageview

Flutter PageView not swipeable on web (using chrome web browser)


i want to create my portfolio using flutter web i use from page view to swipe between pages but page view not swiping this is my code i flow this guid but it not work for meFlutter PageView not swipeable on web (desktop mode)

class CustomPageView extends StatefulWidget {
  const CustomPageView({Key? key}) : super(key: key);

  @override
  State<CustomPageView> createState() => _CustomPageViewState();
}

class _CustomPageViewState extends State<CustomPageView> {
  var controller;
  @override
  void initState() {
    controller = PageController(
      initialPage: 0,
      keepPage: true,
    );
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: customAppBar(),
      key: Globals.scaffoldKey,
      endDrawer: const CustomEndDrawer(),
      backgroundColor: whiteColor,
      body: PageView(
          controller: controller,
          scrollDirection: Axis.vertical,
          onPageChanged: (index) {
            print(index);
          },
          // ignore: prefer_const_literals_to_create_immutables
          children: [
            const Home(),
            Container(
              color: Colors.red,
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
            )
          ]),
    );
  }
}

Solution

  • By default none of the scrollable widgets are scrolled with mouse on web. You can override the behavior by wrapping your widget a configuration.

    import 'package:flutter/gestures.dart';
    import 'package:flutter/material.dart';
    
    class MouseDraggableScrollBehavior extends MaterialScrollBehavior {
    @override
    Set<PointerDeviceKind> get dragDevices => <PointerDeviceKind>{
        PointerDeviceKind.touch,
        PointerDeviceKind.mouse,
      };
    }
    

    After that wrap your PageView:

    ScrollConfiguration(
       behavior: MouseDraggableScrollBehavior(),
       child: yourPageViewWidget,
    )