定义一个单独的KeepAliveWrapper.dart 的tool文件
import 'package:flutter/material.dart';
class KeepAliveWrapper extends StatefulWidget {
const KeepAliveWrapper(
{Key? key, @required this.child, this.keepAlive = true})
: super(key: key);
final Widget? child;
final bool keepAlive;
@override
State<KeepAliveWrapper> createState() => _KeepAliveWrapperState();
}
/**
* AutomaticKeepAliveClientMixin 可以快速的实现页面缓存功能,
* 但是通过混入的方式实现不是很优雅,所以我们有必要对
* AutomaticKeepAliveClientMixin 混入进行封装
*/
class _KeepAliveWrapperState extends State<KeepAliveWrapper>
with AutomaticKeepAliveClientMixin {
@override
Widget build(BuildContext context) {
super.build(context);
return widget.child!;
}
@override
bool get wantKeepAlive => widget.keepAlive;
@override
void didUpdateWidget(covariant KeepAliveWrapper oldWidget) {
if (oldWidget.keepAlive != widget.keepAlive) {
// keepAlive 状态需要更新,实现在 AutomaticKeepAliveClientMixin 中
updateKeepAlive();
}
super.didUpdateWidget(oldWidget);
}
}
在使用时传入它要缓存的子元素,以及是否开启缓存两个参数,一般为了防止TabBar点击之后切换回来长列表的滚动条又回到最上方,给用户带来不好的体验。
KeepAliveWrapper(
/**
* // 自定义缓存组件,防止点击TabBar之后页面跳回最上方
*/
keepAlive: true,
child: ListView(
children: const [
ListTile(
title: Text("关注列表1"),
),
ListTile(
title: Text("关注列表2"),
),
ListTile(
title: Text("关注列表3"),
),
ListTile(
title: Text("关注列表4"),
),
ListTile(
title: Text("关注列表5"),
),
ListTile(
title: Text("关注列表6"),
),
ListTile(
title: Text("关注列表7"),
),
ListTile(
title: Text("关注列表8"),
),
ListTile(
title: Text("关注列表9"),
),
ListTile(
title: Text("关注列表10"),
),
ListTile(
title: Text("关注列表11"),
),
ListTile(
title: Text("关注列表12"),
),
ListTile(
title: Text("关注列表13"),
),
ListTile(
title: Text("关注列表14"),
),
ListTile(
title: Text("关注列表15"),
),
ListTile(
title: Text("关注列表16"),
),
ListTile(
title: Text("关注列表17"),
),
ListTile(
title: Text("关注列表18"),
)
],
),
),