如何解决传递 scrollController 时 CustomScrollView 滚动行为会发生变化
我正在尝试自动滚动到 SliverList
内的 CustomScrollView
的末尾。 SliverList
本身没有控制器属性,因此我必须将 ScrollController
传递给 CustomScrollView
。
问题是当我将控制器传递给 CustomScrollView
时,它的行为会发生变化,它不再滚动外部列表,也不会导致 SliverAppBar
小部件折叠。如何自动滚动 SliverList
并像以前一样保持 CustomScrollView
的行为?
这是我的代码:
class _MyHomePageState extends State<MyHomePage> {
ScrollController _scrollController = ScrollController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),),floatingActionButton: FloatingActionButton(
onPressed: () {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,curve: Curves.easeOut,duration: const Duration(seconds: 1),);
},body: NestedScrollView(
headerSliverBuilder: (BuildContext context,bool innerBoxIsScrolled) {
return <Widget>[
SliverAppBar(
expandedHeight: 230.0,pinned: true,flexibleSpace: FlexibleSpaceBar(
title: Text('SliverAppBar Expand'),)
];
},body: CustomScrollView(
//When controller is passed to CustomScrollView,its behavior changes
// controller: _scrollController,slivers: [
//Some widgets are here
SliverList(
delegate: SliverChildBuilderDelegate(
(context,index) {
return Container(
height: 80,color: Colors.primaries[index % Colors.primaries.length],alignment: Alignment.center,child: Text(
'Item : $index',);
},childCount: 20,],);
}
}
解决方法
我想您可能会注意到此处示例的解释:NestedScrollView class
// 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.
// The PageStorageKey should be unique to this ScrollView;
// it allows the list to remember its scroll position when
// the tab view is not on the screen.
和
// This Builder is needed to provide a BuildContext that is
// "inside" the NestedScrollView,so that
// sliverOverlapAbsorberHandleFor() can find the
// NestedScrollView.
正确的方法是获取CustomScrollView使用的控制器,而不是添加一个新的控制器。
可以通过在 CustomScrollView 上方添加一个 Builder
并将控制器分配给 _scrollController 来完成。
...
body: NestedScrollView(
...
body: Builder(
builder: (context){
_scrollController = PrimaryScrollController.of(context);
return CustomScrollView(
...
},),...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。