Several methods for Flutter to implement page state caching

insert image description here

When using the BottomNavigationBar component for page switching, the component will be destroyed when the page is switched away, and it will be recreated when the page is switched back. How to keep the page switched away without destroying the component (cache state)?

There are two methods:

1. Use the IndexedStack component to cache the page.
The IndexedStack component will create the component at one time, stack windows, and switch to display the corresponding window through index

List<Widget> _MainList = [HomePage(), KnowledgePage(), MenstrualCalendarPage(), UserPage()];
int currentIndex = 0;

body: IndexedStack(
  index: currentIndex,
  children: _MainList,
),

insert image description here
2. Use the PageView component, and mix the component into AutomaticKeepAliveClientMixin for use together** (recommended)**

List<Widget> _MainList = [HomePage(), KnowledgePage(), MenstrualCalendarPage(), UserPage()];
int currentIndex = 0;
late PageController _pageController;

@override
void initState() {
    
    
  super.initState();
  this._pageController = PageController(initialPage: this.currentIndex, keepPage: true);
}
@override
void dispose() {
    
    
  _pageController.dispose();
  super.dispose();
}
  
Scaffold(
	body: PageView(
	 physics: NeverScrollableScrollPhysics(), // 禁止左右滑动切换页面
	  controller: _pageController,
	  children: _MainList,
	),
	bottomNavigationBar: BottomNavigationBar(
	   onTap: (int index) {
    
    
	     setState(() {
    
    
	        this.currentIndex = index;
	        _pageController.jumpToPage(index);
	      });
	    },
	);
);

Then mix in AutomaticKeepAliveClientMixin in the component that needs to be cached

class _MenstrualCalendarPageState extends State<MenstrualCalendarPage> with AutomaticKeepAliveClientMixin {
    
    

  @override
  void initState() {
    
    
    super.initState();
    print('创建分类页面');
  }

  @override
  Widget build(BuildContext context) {
    
    
    super.build(context);
    return Container(child: MyText('缓存的组件'),);
  }
  
  @override
  bool get wantKeepAlive => true; // 是否开启缓存
}

If you find it useful, feel free to give it a thumbs up, thank you for
following me and sharing technical dry goods from time to time~

Scan the QR code to follow the official account
insert image description here

Guess you like

Origin blog.csdn.net/weixin_45295253/article/details/125368884