gpt4 book ai didi

flutter - 传递scrollController 时 CustomScrollView 滚动行为会发生变化

转载 作者:行者123 更新时间:2023-12-02 19:02:39 25 4
gpt4 key购买 nike

我正在尝试自动滚动到 CustomScrollView 内的 SliverList 的末尾。 SliverList 本身没有 Controller 属性,因此我必须将 ScrollController 传递给 CustomScrollView

问题是,当我将 Controller 传递给 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使用的 Controller ,而不是向其中添加新的 Controller 。

可以通过在 CustomScrollView 上方添加 Builder 并将 Controller 分配给 _scrollController 来完成。

...
body: NestedScrollView(
...
body: Builder(
builder: (context){
_scrollController = PrimaryScrollController.of(context);
return CustomScrollView(
...
},
),
),
...

关于flutter - 传递scrollController 时 CustomScrollView 滚动行为会发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65369458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com