keep_alive_wrapper.dart 962 B

123456789101112131415161718192021222324252627282930313233343536
  1. import 'package:flutter/material.dart';
  2. /// 保持页面或列表的缓存 -可用于列表和PageView的子页面
  3. class KeepAliveWrapper extends StatefulWidget {
  4. const KeepAliveWrapper({
  5. Key? key,
  6. this.keepAlive = true,
  7. required this.child,
  8. }) : super(key: key);
  9. final bool keepAlive;
  10. final Widget child;
  11. @override
  12. _KeepAliveWrapperState createState() => _KeepAliveWrapperState();
  13. }
  14. class _KeepAliveWrapperState extends State<KeepAliveWrapper>
  15. with AutomaticKeepAliveClientMixin {
  16. @override
  17. Widget build(BuildContext context) {
  18. super.build(context);
  19. return widget.child;
  20. }
  21. @override
  22. void didUpdateWidget(covariant KeepAliveWrapper oldWidget) {
  23. if(oldWidget.keepAlive != widget.keepAlive) {
  24. // keepAlive 状态需要更新,实现在 AutomaticKeepAliveClientMixin 中
  25. updateKeepAlive();
  26. }
  27. super.didUpdateWidget(oldWidget);
  28. }
  29. @override
  30. bool get wantKeepAlive => widget.keepAlive;
  31. }