Flutter 如何保存滚动视图的位置

Posted on Wed, 25 Dec 2024 11:21:57 +0800 by LiangMingJian


使用 AutomaticKeepAliveClientMixin 保存状态

通过在WidgetState中混入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),
            ));
    }),
参考文件 1: how-to-get-flutter-scrollcontroller-to-save @stackoverflow