tabbar页面每次切换都刷新
时间: 2024-01-15 10:05:32 浏览: 29
TabBar页面切换时,如果每次都刷新,会大大降低应用程序的性能,因此不建议这样做。如果你想要在TabBar页面切换时保留之前的状态,可以考虑使用页面缓存。在 Flutter 中,可以使用 `AutomaticKeepAliveClientMixin` 混入类来实现页面缓存。
具体实现方法如下:
1. 在需要缓存的页面中,混入 `AutomaticKeepAliveClientMixin` 类,并实现 `wantKeepAlive` 方法,返回 `true`:
```
class MyPage extends StatefulWidget {
@override
_MyPageState createState() => _MyPageState();
}
class _MyPageState extends State<MyPage> with AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
// ...
}
```
2. 在 TabBar 页面中,将每个 Tab 对应的页面封装成 KeepAliveWidget 类型,这样就可以保持页面状态:
```
class TabBarPage extends StatefulWidget {
@override
_TabBarPageState createState() => _TabBarPageState();
}
class _TabBarPageState extends State<TabBarPage> {
final List<Widget> _pages = [
KeepAliveWidget(child: MyPage1()),
KeepAliveWidget(child: MyPage2()),
KeepAliveWidget(child: MyPage3()),
];
int _currentIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(
index: _currentIndex,
children: _pages,
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Page 1',
),
BottomNavigationBarItem(
icon: Icon(Icons.mail),
label: 'Page 2',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Page 3',
),
],
),
);
}
}
```
这样,在 TabBar 页面切换时,之前打开的页面状态将会被保留。