我有一个
NestedScrollView
和 SliverAppBar
。 NestedScrollView
的主体是一个带有 CustomScrollView
和 SliverList
的小部件。
我想获取从
ScrollController
到 NestedScrollView
的偏移量,但它只给我偏移量,直到 SliverAppBar
看不见,但之后 SliverList
继续滚动,但 ScrollController
不给出偏移量。
NestedScrollView(
headerSliverBuilder: (_, __) => SliverAppBar(..),
body: RefreshIndicator(
child: CustomScrollView(..),
),
)
CustomScrollView
将自动使用PrimaryScrollController
提供的NestedScrollView
。SliverAppBar
滑入视图和滑出视图时,侦听器将被调用,直到position.extentAfter
等于0.0
,然后它根本不会更新,不无论您向下滚动多远,因为 extentAfter
始终保持在 0.0
。
如何检索
CustomScrollView
内部 NestedScrollView
的滚动位置?
使用
PrimaryScrollController
很重要,因为ScrollController
应该具有PrimaryScrollController
的特征。无论如何,为了让 SliverAppBar
工作,即随着内容滚动到视图之外, NestedScrollView
controller
参数需要以某种方式与 CustomScrollView
controller
(或 primary
)参数相匹配。
任何允许使用
PrimaryScrollController.of(context)
滚动内容的实现都可以。NestedScrollView
才能使 RefreshIndicator
出现在 SliverAppBar
下面。
也许我可以帮助你!
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');
}),
),
)
],
);
},
),
),
),
);
}
在我看来,您需要附加一个
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
滚动。在两个不同的领域取得了成就:
注意,您可以将另一个控制器/侦听器附加到内部
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.