Flutter开发2:导航栏

底部导航栏 BottomNavigationBar

它是属于 Scaffold 中的一个位于底部的控件,与 BottomNavigationBarItem 配合使用

属性名 类型 简介
items List<BottomNavigationBarItem> 底部导航栏展示的内容项
onTap ValueChanged<int> 点击导航栏子项时的回调
currentIndex int 当前选择的子项索引
type BottomNavigationBarType 底部导航栏的类型,fixed、shifting两种
selectedItemColor Color 选中时子项的颜色
unselectedItemColor Color 未选中时子项的颜色
selectedLabelStyle TextStyle 选中时子项文字的style
unselectedLabelStyle TextStyle 未选中时子项文字的style
fixedColor Color type为fixed时导航栏的颜色,默认使用ThemeData.primaryColor
iconSize double 图标大小

需要注意,BottomNavigationBar如果不指定type,则当items小于4个时,type属性值为fixed,大于或等于4个时,则值会变为shifting,通常需要显式的将type设置为fixed以达到期望的效果

BottomNavigationBarItem 属性

属性名 类型 简介
icon Widget 要显示的图标
title Widget 要显示的文字
activeIcon Widget 选中时展示的icon
backgroundColor Color type为shifting时的背景颜色
 int _currentBottomBarIndex = 0;
 BottomNavigationBar(
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: '首页',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.park),
            label: '广场',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.shopping_cart),
            label: '购物车',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person),
            label: '我的',
          )
        ],
        type: BottomNavigationBarType.fixed,
        selectedItemColor: Colors.purple,
        unselectedItemColor: Colors.grey,
        selectedFontSize: 16,
        unselectedFontSize: 14,
        currentIndex: _currentBottomBarIndex,
        selectedLabelStyle: const TextStyle(color: Colors.purple),
        unselectedLabelStyle: const TextStyle(color: Colors.grey),
        onTap: (index){
          setState(() {
            _currentBottomBarIndex = index;
          });
        },
      ),
WX20220424-113110.png

任意导航栏 TabBar

它是切换Tab页的入口,通常会放到AppBar控件中的bottom属性中使用,也可放到其他布局位置,其子元素按水平横向排列布局,一般会与TabBarView组合使用,形成联动效果。

属性名 类型 简介
tabs List<Widget> 要显示的Tab列表,通常使用Tab控件
controller TabController 要显示的文字
isScrollable bool 是否可滚动
indicatorColor Color 指示器颜色
indicatorWeight double 指示器厚度
indicatorPadding EdgeInsetsGeometry 底部指示器的Padding
indicator Decoration 指示器decoration,例如边框等
indicatorSize TabBarIndicatorSize 指示器大小计算方式
labelColor Color 选中Tab文字颜色
labelStyle TextStyle 选中Tab文字Style
unselectedLabelColor Color 未选中Tab中文字颜色
unselectedLabelStyle TextStyle 未选中Tab中文字style

TabBar + TabBarView

TabBarView是Tab页的内容容器,其内放置Tab页的主体内容。

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {

  @override
  void initState() {
    super.initState();
    controller = TabController(length: 4,vsync: this);
  }

  TabController controller;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Widget"),
        bottom: TabBar(
          controller: controller,
            tabs:[
              Tab(text: "社会心理学",),
              Tab(text: "发展心理学",),
              Tab(text: "变态心理学",),
              Tab(text: "健康心理学",)
            ]
        ),
      ),
      body: TabBarView(
        controller: controller,
        children: <Widget>[
          Icon(Icons.access_time),
          Icon(Icons.accessibility_new),
          Icon(Icons.keyboard),
          Icon(Icons.airline_seat_flat),
        ],
      ),
    );
  }
}

当我们不需要通过代码去手动切换Tab页时,可使用默认的控制器DefaultTabController

TabBar + PageView


保存状态

直接使用如上方案,在每次切换Page 页时,页面都会重新创建,initState重新执行,想要提升性能,达到我们期望的效果,则需要使用如下步骤保存状态

在State类上混入AutomaticKeepAliveClientMixin类
重写wantKeepAlive方法,并返回true
在页面的build方法中,调用super.build

iOS 风格导航栏

关于部分iOS风格的控件,可以查看 Cupertino 官方文档

Flutter 官方正在逐渐完善Cupertino风格的控件体系,但总的来说仍然存在一些问题,目前还不太建议使用,这里仅作为介绍。

CupertinoTabBar + CupertinoTabView 示例

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '页面框架',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}


class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return CupertinoTabScaffold(
      tabBar: CupertinoTabBar(
        items: const [
          BottomNavigationBarItem(label: "首页", icon: Icon(Icons.home)),
          BottomNavigationBarItem(label: "我的", icon: Icon(Icons.account_box)),
        ],
      ),
      tabBuilder: (BuildContext context, int index) {
        return CupertinoTabView(
          builder: (context) {
            switch (index) {
              case 0:
                return const FirstPage();
                break;
              case 1:
                return const SecondPage();
                break;
              default:
                return const FirstPage();
            }
          },
        );
      },
    );
  }
}

class FirstPage extends StatefulWidget {
  const FirstPage({Key? key}) : super(key: key);

  @override
  _FirstPageState createState() => _FirstPageState();
}

class _FirstPageState extends State<FirstPage> {
  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold (
      navigationBar: const CupertinoNavigationBar(
        middle: Text("首页"),
        transitionBetweenRoutes: false,
      ),
      child: Center(
        child: CupertinoButton (
          child: const Text("跳转新页"),
          onPressed: () {
            Navigator.of(context,rootNavigator: true).push(
                CupertinoPageRoute(
                    builder: (BuildContext context) {
                      return const NewPage();
                    }
                )
            );
          },
        ),
      ),
    );
  }
}

class SecondPage extends StatefulWidget {
  const SecondPage({Key? key}) : super(key: key);

  @override
  _SecondPageState createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> {
  @override
  Widget build(BuildContext context) {
    return const CupertinoPageScaffold (
      navigationBar: CupertinoNavigationBar(
        middle: Text("我的"),
      ),
      child: Center(
          child: Text("我的页面")
      ),
    );
  }
}

class NewPage extends StatelessWidget {
  const NewPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: const CupertinoNavigationBar(
        transitionBetweenRoutes: false,
      ),
      child: Container(
        alignment: Alignment.center,
        child: const Text("新页面"),
      ),
    );
  }
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,826评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,968评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,234评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,562评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,611评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,482评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,271评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,166评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,608评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,814评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,926评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,644评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,249评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,866评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,991评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,063评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,871评论 2 354

推荐阅读更多精彩内容