keep_alive_wrapper.dart 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import 'package:flutter/material.dart';
  2. /// 保持页面或列表的缓存 -可用于列表和PageView的子页面
  3. // ignore: slash_for_doc_comments
  4. /** 使用示例
  5. *
  6. @override
  7. Widget build(BuildContext context) {
  8. var children = <Widget>[];
  9. for (int i = 0; i < 6; ++i) {
  10. //只需要用 KeepAliveWrapper 包装一下即可
  11. children.add(KeepAliveWrapper(child:Page( text: '$i'));
  12. }
  13. return PageView(children: children);
  14. }
  15. */
  16. class KeepAliveWrapper extends StatefulWidget {
  17. const KeepAliveWrapper({
  18. Key? key,
  19. this.keepAlive = true,
  20. required this.child,
  21. }) : super(key: key);
  22. final bool keepAlive;
  23. final Widget child;
  24. @override
  25. _KeepAliveWrapperState createState() => _KeepAliveWrapperState();
  26. }
  27. class _KeepAliveWrapperState extends State<KeepAliveWrapper>
  28. with AutomaticKeepAliveClientMixin {
  29. @override
  30. Widget build(BuildContext context) {
  31. super.build(context);
  32. return widget.child;
  33. }
  34. @override
  35. void didUpdateWidget(covariant KeepAliveWrapper oldWidget) {
  36. if(oldWidget.keepAlive != widget.keepAlive) {
  37. // keepAlive 状态需要更新,实现在 AutomaticKeepAliveClientMixin 中
  38. updateKeepAlive();
  39. }
  40. super.didUpdateWidget(oldWidget);
  41. }
  42. @override
  43. bool get wantKeepAlive => widget.keepAlive;
  44. }