七、Flutter优化Tabbar

目录
一、Tabbar问题
二、底部Tabbar
三、顶部Tabbar

最近一直忙于基于FreeSwitch的Sip融合通信了,没有及时更新文章。技术的更新太快了,每天都会出现各种框架和技术技巧,是学不完的,也只能先精通一种语言,然后熟练应用于工作中,这个时候可以学一些相关的技术,就显得你比较牛了。闲言少叙,言归正传,今天介绍如何优化Tabbar并没有从底层分析,只是快速解决了这类问题。

一、Tabbar问题

先看我写的《六、Flutter自定义Tabbar》,效果图如下:


七、Flutter优化Tabbar_第1张图片
Tabbar.jpg

底部Tabbar切换时currentPage会被销毁,重新加载页面。底部Tabbar每切换一次,就请求一次网络,造成了资源浪费,用户体验也比较差。
顶部Tabbar和底部Tabbar存在的问题几乎一样,都是切换时页面重复刷新。

二、底部Tabbar
底部Tabbar只需要currentPage不重复渲染就可以了,可以使用IndexedStack来解决这个问题。

页面重复渲染的代码:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromRGBO(244, 245, 245, 1.0),
      bottomNavigationBar: BottomNavigationBar(
        type:BottomNavigationBarType.fixed,
        currentIndex: currentIndex,
        items:_bottomTabs,
        onTap: (index){
          setState(() {
           currentIndex = index;
           currentPage = _tabs[currentIndex]; 
          });
        },
       fixedColor: Colors.green,
      ),
      body:currentPage
    );
  }

缓存页面的代码:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromRGBO(244, 245, 245, 1.0),
      bottomNavigationBar: BottomNavigationBar(
        type:BottomNavigationBarType.fixed,
        currentIndex: currentIndex,
        items:_bottomTabs,
        onTap: (index){
          setState(() {
           currentIndex = index;
          });
        },
       fixedColor: Colors.green,
      ),
      body:IndexedStack(
        children: [
           TopBarPage(),
           AudioBook(),
           Team(),
           Fair(),
           Mine()
        ],
        index: currentIndex,
      )
    );
  }

三、顶部Tabbar
顶部Tabbar加载子页面使用的是TabBarView,这里使用AutomaticKeepAliveClientMixin保证子页面不再重复渲染。

class Home extends StatefulWidget {
  _HomeState createState() => _HomeState();
}

class _HomeState extends State with AutomaticKeepAliveClientMixin{
  @override
  Widget build(BuildContext context) {
    super.build(context);
    .....................................
    .....................................
    .....................................
}

  @override
  bool get wantKeepAlive => true;
}

总结:这是我写关于Flutter的第七篇文章了,对Flutter总算有个大概的了解了,算是入门了。接下来会写一些原理性的文章,或者写一些小的Widget,希望在阅读的你早日掌握Flutter,成为Flutter大神。

七、Flutter优化Tabbar_第2张图片
关注公众号,查看更多内容.jpg

你可能感兴趣的:(七、Flutter优化Tabbar)