Flutter PageController nextPage, previousPage, animateToPage are not working

Issue

I am trying to make the page switch on mouse scroll on web (snap) since it is not supported by default in flutter. However, the animateTo method is not causing any effect, and the scrolling is continuing.
I tried the animateTo using a button and it worked. not really clear to me why it is not working this way.

code is as follows:

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;

class MainView extends StatelessWidget {
  MainView({Key? key}) : super(key: key);
  final PageController controller = PageController(initialPage: 0);

  @override
  Widget build(BuildContext context) {
    if (kIsWeb) {
      // running on the web!
      return Listener(
        onPointerSignal: (pointerSignal) {
          if (pointerSignal is PointerScrollEvent) {
            if (pointerSignal.scrollDelta.dy > 0) {
              // scroll down
              controller.nextPage(
                  duration: const Duration(seconds: 1), curve: Curves.ease);
            } else if (pointerSignal.scrollDelta.dy < 0) {
              controller.previousPage(
                  duration: const Duration(seconds: 1), curve: Curves.ease);
            }
          }
        },
        child: PageView(
          scrollDirection: Axis.vertical,
          pageSnapping: false,
          controller: controller,
          children: const <Widget>[
            Center(
              child: Text('First Page'),
            ),
            Center(
              child: Text('Second Page'),
            ),
            Center(
              child: Text('Third Page'),
            )
          ],
        ),
      );
    } else {
      // NOT running on the web! You can check for additional platforms here.
      return const Container();
    }
  }
}```

Solution

If I understand you correctly, you want to animate to a page when scrolling with the mouse using pointer signal events. One option is to add physics: const NeverScrollableScrollPhysics(), to your PageView Widget which will disable any default scrolling behavior.

Hopefully, this is what you’re looking for!

Answered By – Will Hlas

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *