如何从NestedScrollView中的CustomScrollView获取偏移量

时间:2019-03-22 20:17:32

标签: flutter

我有一个NestedScrollView和一个SliverAppBarNestedScrollView的主体是带有CustomScrollViewSliverList的小部件。

我想从提供给ScrollController的{​​{1}}得到偏移,但是它只给我偏移,直到NestedScrollView消失,之后{{ 1}}继续滚动,但是SliverAppBar没有给出偏移量。

2 个答案:

答案 0 :(得分:1)

也许我可以帮助您!

Widget build(BuildContext context) {
  return Scaffold(
    body: NestendScrollView(
      headerSliverBuilder: (BuildContext context, bool value) {
        return <Widget>[
           SliverAppBar(),
        ];
      },
        body: SafeArea(
          child: Builder(
            builder: (context) {
              final _scr = PrimaryScrollController.of(context);
              _scr.addListener(() {
                if (_scr.position.pixels == _scr.position.maxScrollExtent) {
                  print('At DOWNW!!!');
                }
              });

              return CustomScrollView(
                controller: _scr,
                slivers: <Widget>[
                  SliverOverlapAbsorber(
                    handle: NestedScrollView.sliverOverlapAbsorberHandleFor(
                      context,
                    ),
                  ),
                  SliverList(
                    delegate: SliverChildListDelegate(
                      List.generate(100, (int index) {
                        return Text('ITEM -> $index');
                      }),
                    ),
                  )
                ],
              );
            },
          ),
        ),
    ),
  );
}

答案 1 :(得分:0)

在我看来,您将需要附加NotificationListener<ScrollNotification>来跟踪内部CustomScrollView的偏移量

NestedScrollView(
  controller: // PrimaryScrollController
  headerSliverBuilder: (_, __) => SliverAppBar(..),
  body: RefreshIndicator(
    child: NotificationListener<ScrollNotification>(
      child: CustomScrollView(..),
      onNotification: (ScrollNotification scrollInfo) {
        double customPixel = scrollInfo.metrics.pixels; // same as offset
        return false;
      },
    )
  )
)

因此,正如您提到的,NestedScrollView控制器的侦听器将仅响应SliverAppBar的高度。一旦看不见,ScrollNotification就会启动并开始响应CustomScrollView滚动。在两个单独的区域中完成:

  1. NestedScrollView的SliverAppBar的PrimaryScrollController-监听器
  2. CustomScrollView的本身的NotificationListener-ScrollNotification

请注意,您可以在内部CustomScrollView上附加另一个控制器/侦听器,但这与以下注意事项相反:https://api.flutter.dev/flutter/widgets/NestedScrollView-class.html

return CustomScrollView(
  // The "controller" and "primary" members should be left
  // unset, so that the NestedScrollView can control this
  // inner scroll view.
  // If the "controller" property is set, then this scroll
  // view will not be associated with the NestedScrollView.