Flutter 如何保存滚动视图的位置
Posted on Wed, 25 Dec 2024 11:21:57 +0800 by LiangMingJian
Flutter 如何保存滚动视图的位置
使用 AutomaticKeepAliveClientMixin 保存状态
通过在Widget
的State
中混入AutomaticKeepAliveClientMixin
,再重写wantKeepAlive
的值为true
,这样来保留列表项的状态。
class GetListView extends StatefulWidget{
@override
State<StatefulWidget> createState() =>_GetListViewState();
}
class _GetListViewState extends State<GetListView> with AutomaticKeepAliveClientMixin<GetListView>{
@override
Widget build(BuildContext context){
return ListView.builder(
itemCount: 2000,
itemBuilder: (context, i) {
return ListTile(
title: Text(
i.toString(),
textScaleFactor: 1.5,
style: TextStyle(color: Colors.blue),
));
});
}
@override
bool get wantKeepAlive => true;
}
使用 PageStorageKey 保存偏移
通过在列表builder
中使用PageStorageKey
手动保存偏移值,这样来保留列表项的状态。
ListView.builder(
key: PageStorageKey<String>("controllerA"),
controller: ScrollController(keepScrollOffset: true),
itemCount: 2000,
itemBuilder: (context, i) {
print("Rebuilded 1");
return ListTile(
title: Text(
i.toString(),
textScaleFactor: 1.5,
style: TextStyle(color: Colors.blue),
));
}),