Flutter实现切换页面/tab后保持原页面状态
- 发表于
- flutter
在Flutter应用中,导航栏或Tab切换页面后默认情况下会丢失原页面状态,即每次进入页面时都会重新初始化状态,显然这样增加了额外的开销,并且带来了不好的用户体验。页面保持状态,不重绘,在app中很重要,比如看着朋友圈/热门微博,看到一半,需要切换到其他tab设置点东西,再切换回来,这个时候肯定不需要页面重绘,然后从头开始看吧,而是希望直接接着前面的状态继续看。
这样我们就需要用到页面保持状态,使他不销毁不重绘。
AutomaticKeepAliveClientMixin
我们只需要在导航内需要保持页面状态的子页State
中,继承AutomaticKeepAliveClientMixin
并重写wantKeepAlive
为true
即可。
BottomNavigationBar+PageView+AutomaticKeepAliveClientMixin
sub_demo.dart
class DemoPage extends StatefulWidget {
_DemoPageState createState() => _DemoPageState();
}
class _DemoPageState extends State<DemoPage> with AutomaticKeepAliveClientMixin{//要点1
int _count = 0;
@override
bool get wantKeepAlive => true;//要点2
@override
Widget build(BuildContext context) {
super.build(context);//要点3
return Scaffold(
appBar: AppBar(title:Text('Demo Page')),
body: Center(child:Text('当前计数:$_count')),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: (){
setState(() {
_count++;
});
},
),
);
}
}
上面我们已经标出三个重要的位置,这里再强调一下:
- with AutomaticKeepAliveClientMixin{
- bool get wantKeepAlive => true;
- super.build(context);
补充
上面的是用于两级页面/tab切换保存状态的,但如果是涉及到三级切换,即下导航,上导航,子导航这种,详细参考这篇文章:
原文连接:Flutter实现切换页面/tab后保持原页面状态
所有媒体,可在保留署名、
原文连接
的情况下转载,若非则不得使用我方内容。