Flutter底部Tab切换保持页面状态的几种方法
flutter底部导航默认只加载当前页面,切换到其他页面后,上一个页面就会被销毁,当我们返回到上一个页面时,会重新进行数据请求。这样子每次进行页面访问时都会进行一次数据请求,非常的浪费时间,因此,我们想要访问其他页面时,上一个页面不被销毁,再次访问时不需要重新加载数据。
IndexedStack 保持页面状态
IndexedStack 和 Stack 一样,都是层布局控件, 可以在一个控件上面放置另一个控件,但唯一不同的是 IndexedStack 在同一时刻只能显示子控件中的一个控件,通过 Index 属性来设置显示的控件IndexedStack 来保持页面状态的优点就是配置简单。IndexedStack 保持页面状态的缺点就是不方便单独控制每个页面的状态,相当于直接加载了Tab导航下的所有页面。
只需要修改body中即可
body:IndexedStack(
children: this._pageList,
index: _currentIndex,
),
AutomaticKeepAliveClientMixin 保持页面状态
AutomaticKeepAliveClientMixin 结合 tab 切换保持页面状态相比 IndexedStack 而言配置起来稍
微有些复杂。它结合底部 BottomNavigationBar 保持页面状态的时候需要进行如下配置。好处在于可以对特定的几个页面进行状态设置,保持页面状态。
class _TabsState extends State<Tabs> {
int _currentIndex = 0;
List<Widget> _pageList = [HomePage(), CatrgoryPage(), CartPage(), UserPage()];
//创建页面控制器
late PageController _pageController;
@override
void initState() {
super.initState();
//初始化页面控制器
_pageController = PageController(initialPage: _currentIndex);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('jdshop'),
),
// body: _pageList[_currentIndex],
body: PageView(
controller: _pageController,
children: _pageList,
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
//页面控制器进行转跳
_pageController.jumpToPage(index);
});
},
type: BottomNavigationBarType.fixed,
fixedColor: Colors.red,
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: "首页"),
BottomNavigationBarItem(icon: Icon(Icons.category), label: "分类"),
BottomNavigationBarItem(
icon: Icon(Icons.shopping_cart), label: "购物车"),
BottomNavigationBarItem(icon: Icon(Icons.people), label: "我的"),
]));
}
}
除此之外还需要在每个需要保持状态的页面进行设置
class CatrgoryPage extends StatefulWidget {
CatrgoryPage({
Key? key}) : super(key: key);
@override
State<CatrgoryPage> createState() => _CatrgoryPageState();
}
class _CatrgoryPageState extends State<CatrgoryPage>
with AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
}