前言

在flutter项目中使用ListView或者PageView等有滚动条组件的时候,切换页面的时候,再切换回来会丢失之前的滑动状态,这个时候就需要需要使用缓存功能

缓存类

import 'package:flutter/material.dart';class KeepAliveWrapper extends StatefulWidget { const KeepAliveWrapper( {Key? key,  this.child, this.keepAlive = true}) : super(key: key); final Widget? child; final bool keepAlive;  State<KeepAliveWrapper> createState() => _KeepAliveWrapperState();}class _KeepAliveWrapperState extends State<KeepAliveWrapper> with AutomaticKeepAliveClientMixin {  Widget build(BuildContext context) { return widget.child!; }  bool get wantKeepAlive => widget.keepAlive;}

使用

在需要缓存的组件使用KeepAliveWrapper包裹一下即可

@overrideWidget build(BuildContext context) {return KeepAliveWrapper(child: Scaffold(body: Stack(children: [_homePage(), _appBar()],),));}