本文实例为大家分享了flutter实现切换页面缓存的具体代码,供大家参考,具体内容如下 一、实现底部导航栏切换页面缓存 实现底部导航栏切换页面缓存需要在pubspc.yamal中导入 proste_i
          本文实例为大家分享了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切换页面缓存
顶部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),
        ));
  }
}
文章只介绍了如何实现切换页面缓存,其他相关具体页面实现在这里就不赘述了,有需要的可以自己实现一下试一试。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。
