Flutter CustomScrollView在列表开头添加项目时如何保持视口



问题:例如,有一个包含100条消息的列表。CCD_ 1的当前视口显示消息50->60.当将新项目添加到列表的开头时,视口跳到消息49(旧)->59(旧)(因为滚动偏移没有改变,所以它向下移动内容)。

预期:添加项目后,视口应保持显示消息50(旧)->60岁(老)。

我该如何实现?

如果您不介意使用两个列表。尝试使用centerKeyCustomScrollView。第一个列表用于新项目,第二个列表用于初始项目。将新项目添加到起点时,只需将项目添加到第一个列表,视口就不会跳转。

@override
Widget build(BuildContext context) {
const Key centerKey = ValueKey('second-sliver-list');
return Scaffold(
body: CustomScrollView(
center: centerKey,
slivers: [
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
final item = newList[index];
return ListTile(
title: Text('${item.id} ${item.name}'),
);
},
childCount: newList.length,
),
),
SliverList(
key: centerKey,
delegate: SliverChildBuilderDelegate(
(context, index) {
final item = myList[index];
return ListTile(
title: Text('${item.id} ${item.name}'),
);
},
childCount: myList.length,
),
),
],
),
);
}

最新更新