Flutter使用PagedListView时分页后动态日期Text部件消失如何解决
问题原因
日期标题消失的核心原因是你依赖了全局的_dateMap缓存已出现过的日期:PagedListView的item是懒加载的,滚动时超出屏幕的item会被销毁,再次滚回屏幕时会触发重建,此时同日期的首个item因为日期已经被存入_dateMap,不会再生成标题;加载下一页触发列表整体重绘时也会触发相同逻辑,导致之前的标题全部消失。
解决方案
改用相邻元素日期对比的逻辑判断是否需要展示标题,不需要额外的缓存map,每次构建item时直接和当前已加载列表的上一个item的日期比对即可,逻辑完全和列表数据绑定,不会因为滚动回收、加载新页丢失标题。
修改后的代码如下:
Expanded( child: Container( padding: const EdgeInsets.only(bottom: 10.0), child: PagedListView<int, Content>( pagingController: _pagingController, builderDelegate: PagedChildBuilderDelegate<Content>( itemBuilder: (context, item, index) { // 替换原有_flag的判断逻辑,改为相邻日期比对 bool needShowDateHeader = false; if (index == 0) { // 第一个item一定显示日期头 needShowDateHeader = true; } else { // 和上一个item的日期比对,不一致就显示日期头 final prevItem = _pagingController.itemList![index - 1]; if (prevItem.date.toString() != item.date.toString()) { needShowDateHeader = true; } } return Column( children: [ Visibility( visible: needShowDateHeader, child: Container( margin: const EdgeInsets.only(top: 15, bottom: 15), child: Center( child: Text( item.date.difference(DateTime.now()).inDays == 0 ? 'Today' : item.date.difference(DateTime.now()).inDays == -1 ? 'Yesterday' : DateFormat('dd-MMM-yyyy').format(item.date).toString(), style: Theme.of(context).textTheme.subtitle2, ), ), ), ), Padding( padding: const EdgeInsets.only(top: 2.5, bottom: 2.5), child: AccountTitle2( reference: item.reference.toString(), accountNo: item.accountNo, transactionType: item.narration, date: item.date.toString(), time: item.time, withdraw: item.withdraw, deposit: item.deposit, ), ) ], ); } ) ), ), )
注意事项
请确保后端返回的列表是按日期顺序排列的,如果后端返回的数据顺序乱序,可以在分页请求拿到新数据后,把全量已加载的数据按日期排序后再赋值给_pagingController.itemList,避免出现同一个日期拆分多个分组的问题。
内容的提问来源于stack exchange,提问作者I don't know
相关产品推荐
相关产品推荐

