一、IndexedStack 保持页面状态
// IndexedStack 是一个层布局控件,与 Stack 类似。
// 它允许在一个控件上放置另一个控件,但与 Stack 不同的是,
// 在同一时刻,IndexedStack 只能显示其中一个子控件,可以通过 Index 属性来设置。
//
// 使用 IndexedStack 保持页面状态的优点是它配置简单。
// 但缺点是它不方便单独控制每个页面的状态。
int _currentIndex = 0;
List<Widget> _pageList = [
HomePage(),
CategoryPage(),
CartPage(),
UserPage()
];
// 使用 IndexedStack 控件
body: IndexedStack(
index: this._currentIndex,
children: _pageList,
),
二、AutomaticKeepAliveClientMixin 保持页面状态
// AutomaticKeepAliveClientMixin 结合 tab 切换时能够保持页面状态。
// 与 IndexedStack 相比,配置起来稍微复杂些。
// 当与底部 BottomNavigationBar 一起使用以保持页面状态时,需要进行以下配置。
var _pageController;
void initState() {
super.initState();
_pageController = new PageController(initialPage: _currentIndex);
}
// 使用 PageView 控件
body: PageView(
controller: _pageController,
children: this._pageList,
onPageChanged: (index) {
_currentIndex = index;
},
),
// 使用 BottomNavigationBar 控件
bottomNavigationBar: BottomNavigationBar(
currentIndex: this._currentIndex,
onTap: (index) {
setState(() {
_pageController.jumpToPage(this._currentIndex);
});
},
),
三、使用 AutomaticKeepAliveClientMixin 保存页面状态
// 当需要保持页面状态时,可以在页面的 State 类中引入 AutomaticKeepAliveClientMixin。
// 通过覆盖 wantKeepAlive 方法并返回 true 来告诉 Flutter 框架保持页面状态。
class _HttpPage extends State with AutomaticKeepAliveClientMixin {
// 保持页面状态
bool get wantKeepAlive => true;
}