Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - How to sync two or more PageControllers

Tags:

flutter

In Flutter I can´t assing the same PageController to many PageView. So in need to use two or more PageControllers.

I need to synchronize my ViewPages so that when I slide one another it also slides

How can I sync two or more PageController or PageView?

What I want is every PageView can control others PageView make them all sync no matter which slide.

So if a have A, B and C PageView and I slide A then B and C slides as well... if I slide B then A and C slides... and so on.

like image 553
Oscar Méndez Avatar asked Oct 25 '25 05:10

Oscar Méndez


2 Answers

You can reference https://github.com/braulio94/menu_flutter
The trick is use NotificationListener to listen ScrollUpdateNotification
and compare two page

_backgroundPageController.page != _pageController.page

code snippet at line 183

new NotificationListener<ScrollNotification>(
          onNotification: (ScrollNotification notification) {
            if (notification.depth == 0 &&
                notification is ScrollUpdateNotification) {
              selectedIndex.value = _pageController.page;
              if (_backgroundPageController.page != _pageController.page) {
                _backgroundPageController.position
                    // ignore: deprecated_member_use
                    .jumpToWithoutSettling(_pageController.position.pixels /
                    _kViewportFraction);
              }
              setState(() {});
            }
            return false;
          }

full code
https://github.com/braulio94/menu_flutter/blob/master/lib/screens/pager.dart

enter image description here

like image 72
chunhunghan Avatar answered Oct 26 '25 18:10

chunhunghan


To sync two pageviews (in case you want to use different viewfractions for example) create two controllers, upper with view fraction 0,7 and bottom with 1.0 Now to sync add listener to upper and get current scroll offset value.

   @override
  void initState() {
    super.initState();
       _controller_upper = new PageController(viewportFraction: 0.7);
    _controller_bottom = new PageController();
    _controller.addListener(_onScroll);
  }

  void _onScroll() {
    scrollValue = _controller.page;
    //page returns value between 0 to 1 for 1st page, 1 to 2 for second and s on, need to multiply it by screen width
    _controller_bottom.jumpTo(scrollValue*MediaQuery.of(context).size.width);
  }
like image 35
voytez Avatar answered Oct 26 '25 19:10

voytez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!