您好,登录后才能下订单哦!
本文小编为大家详细介绍“flutter如何实现切换页面缓存”,内容详细,步骤清晰,细节处理妥当,希望这篇“flutter如何实现切换页面缓存”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
实现底部导航栏切换页面缓存需要在pubspc.yamal中导入proste_indexed_stack插件,这个插件可以实现懒加载,比起使用IndexedStack包裹body实现,性能更好。
dependencies:
#懒加载的层叠组件 proste_indexed_stack: //不加版本号可获取最新版本
实现底部导航切换页面缓存只需将body用ProsteIndexedStack包裹一层既可以,注意ProsteIndexedStack的children 是IndexedStackChild类型的,所以中的每一个children 的每一项都需要用IndexedStackChild包裹
示例:
import 'package:flutter/material.dart';
... //其他需要import的内容省略
class RootPage extends StatefulWidget {
@override
_RootPageState createState() => _RootPageState();
}
class _RootPageState extends State<RootPage> {
//底部导航栏数组
final items = [
BottomNavigationBarItem(
icon: Icon(Icons.home),label: '首页',tooltip: ''
),
BottomNavigationBarItem(
icon: Icon(Icons.music_note),label: '音乐',tooltip: ''
),
BottomNavigationBarItem(
icon: Icon(Icons.slow_motion_video),label: '短视频',tooltip: ''
),
BottomNavigationBarItem(
icon: Icon(Icons.account_circle_outlined),label: '我的',tooltip: ''
),
];
//底部导航栏页面
final bodyList = [
IndexedStackChild(child: HomePage()),
IndexedStackChild(child: MusicPage()),
IndexedStackChild(child: TinyVideoPage()),
IndexedStackChild(child: ProfilePage()),
];
//当前选中页面索引
int _currentIndex = 0;
//底部导航栏切换
void _onTap(int index) {
setState(() {
_currentIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: items,
currentIndex: _currentIndex, //当前选中标识符
onTap: _onTap,
type: BottomNavigationBarType.fixed,
),
//ProsteIndexedStack包裹,实现底部导航切换时保持原页面状态
body: ProsteIndexedStack(
index: _currentIndex,
children: bodyList,
),
);
}
}顶部tab切换页面缓存可使用AutomaticKeepAliveClientMixin实现,只需在页面的state中混入AutomaticKeepAliveClientMixin,然后重写wantKeepAlive为true即可。
做了以上配置,你如果在build 中 print 一下,当你切换 tabbar 时,print 就不会打印,也就实现了页面保持状态。
示例:
import 'package:flutter/material.dart';
class ExamplePage extends StatefulWidget {
@override
_ExamplePageState createState() => _RecommendPageState();
}
class _ExmaplePageState extends State<ExamplePage>
with AutomaticKeepAliveClientMixin {
int count = 0;
void add() {
setState(() {
count++;
});
}
@override
bool get wantKeepAlive => true;
@override
void initState() {
super.initState();
print('recommend initState');
}
@override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
body:Center(
child: Text('Example: $count', style: TextStyle(fontSize: 30))
),
floatingActionButton: FloatingActionButton(
onPressed: add,
child: Icon(Icons.add),
));
}
}读到这里,这篇“flutter如何实现切换页面缓存”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。