当我从网络加载新数据时,我正在尝试保存
Listview.builder
的状态。
换句话说,我正在尝试执行惰性加载程序并使用
PageStorageKey
来保存 Listview.builder
的状态,并且它可以部分工作。
所以,问题是当我向右缓慢滚动时,它可以工作并保存当前状态。但是,如果我快速滚动,它会让我回到第一个元素。
这是代码
class CategorySlider extends StatelessWidget {
const CategorySlider({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return SizedBox(
height: 260,
child: BlocBuilder<SliderCubit, SliderState>(
builder: (context, state) {
if (state is SliderLoading) {
return Center();
} else if (state is SliderLoaded) {
return NotificationListener<ScrollNotification>( // It is how I am listening Scrolls
onNotification: (notification) {
if (notification.metrics.extentAfter <= 0.0) {
BlocProvider.of<SliderCubit>(context).sliderLazyLoad(); // Here I am calling data from Network and switch states, while it's loading
return true;
}
return false;
},
child: ListView.builder(
key: const PageStorageKey<String>('Loaded'), //Here is PageStorageKey()
physics: const BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
itemCount: state.model.length,
itemBuilder: (context, index) {
return ListViewCenterFrame(
itemDistance: 25,
child: Stack(
children: [
// My widgets
],
),
index: index,
);
},
),
);
} else {
return const SizedBox();
}
},
),
);
}
}
我在两年后解决了这个错误。显然,用户应该停止滚动才能将
ListView.builder()
的状态保存到PageStorage。因此,当您快速滚动时,实际上并没有停止滚动。
这是我如何使用
ScrollController
解决我的问题:
_scrollController.addListener(() {
final maxScroll = _scrollController.position.maxScrollExtent;
final currentScroll = _scrollController.position.pixels;
//Scrolling is done when currentScroll is equal to maxScroll
if (maxScroll == currentScroll) {
ref
.read(messagesControllerProvider.notifier)
.loadNewMessages(_currentMessages.length);
}
});