Я пытаюсь автоматически прокрутить до конца 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
// 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, а не добавлять к нему новый.
Это можно сделать, добавив Builder
над CustomScrollView) и назначив контроллер _scrollController.
...
body: NestedScrollView(
...
body: Builder(
builder: (context){
_scrollController = PrimaryScrollController.of(context);
return CustomScrollView(
...
},
),
),
...
Спасибо за такой подробный ответ!