简体   繁体   中英

How to sync scroll two SingleChildScrollView widgets

How to sync scroll two SingleChildScrollView widgets?

    new Positioned(
        child: new SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: new Scale() 
            ), 
        ),
    new Positioned(
        child: new SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: new chart()
        )
    )

I need those two widgets to have exactly same scroll position ( both have same width and can be scrolled only horizontally ). It must sync after user action and when changed in code.

like xster said, you have to use scrollcontroller on one scrollview and notification Listener on another scrollview, here is the code.

class StackO extends StatefulWidget {
  // const stack({Key key}) : super(key: key);

  @override
  _StackOState createState() => _StackOState();
}

class _StackOState extends State<StackO> {
  ScrollController _scrollController = new ScrollController();

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          new Positioned(
            child: new SingleChildScrollView(
              controller: _scrollController,
              scrollDirection: Axis.horizontal,
              child: new Scale() // your widgets,
            ),
          ),
          new Positioned(
            child: new NotificationListener<ScrollNotification>(
              onNotification: (ScrollNotification scrollInfo) {
                print('scrolling.... ${scrollInfo.metrics.pixels}');
                _scrollController.jumpTo(scrollInfo.metrics.pixels);
                return false;
              },
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: new chart() // your widgets,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

For input, you control them via a ScrollController passed in as a constructor parameter.

For output, you can use a NotificationListener to listen to movements on one and then use the ScrollController to sync them together.

You can either listen to something like https://docs.flutter.io/flutter/widgets/UserScrollNotification-class.html to keep them tightly bound or wait for https://docs.flutter.io/flutter/widgets/ScrollEndNotification-class.html and then call https://docs.flutter.io/flutter/widgets/ScrollController/animateTo.html on the ScrollController.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM