Flutter自定义BottomNavigatorBar实现首页导航

前言

底部导航,对于做app的同学再熟悉不过了,不过有时候设计为了突出别样的风格,就会来点不一样的,比如下面的效果图。我们使用系统提供的控件,是无法实现的。在看了系统提供的源码后,发现也不是太复杂,于是乎,自己动手实现一个,下面的代码复制过去,改改资源文件是直接可以用的。

效果图

自定义底部导航

定义我们需要的主题


class BottomBarItem {
  BottomBarItem(
      {required this.icon,
      required this.activeIcon,
      required this.title,
      this.activeColor = Colors.blue,
      this.inactiveColor,
      this.textAlign = TextAlign.center,
      this.singleIcon = false});

  final Widget icon;///未选中的状态
  final Widget activeIcon;///选中的状态
  final Widget title;///标题
  final Color activeColor;///选中的颜色
  final Color? inactiveColor;///未选中的颜色
  final TextAlign textAlign;
  final bool singleIcon;///是否只包含icon
}

定义BottomNavigatorBar

///作者  : Pig Huitao
///时间  : 2022/1/6
///邮箱  : pig.huitao@gmail.com
class BottomNavigatorBar extends StatelessWidget {
  const BottomNavigatorBar(
      {Key? key,
      this.selectedIndex = 0,
      this.iconSize = 24,
      this.backgroundColor,
      this.showElevation = true,
      this.animationDuration = const Duration(milliseconds: 270),
      required this.items,
      required this.onItemSelected,
      this.mainAxisAlignment = MainAxisAlignment.spaceBetween,
      this.itemCornerRadius = 50,
      this.containerHeight = 56,
      this.curve = Curves.linear,
      this.singleIcon = false})
      : super(key: key);

  final int selectedIndex;
  final double iconSize;
  final Color? backgroundColor;
  final bool showElevation;
  final Duration animationDuration;
  final List<BottomBarItem> items;
  final ValueChanged<int> onItemSelected;
  final MainAxisAlignment mainAxisAlignment;
  final double itemCornerRadius;
  final double containerHeight;
  final Curve curve;
  final bool singleIcon;

  @override
  Widget build(BuildContext context) {
    final bgColor = backgroundColor ?? Theme.of(context).bottomAppBarColor;
    return Container(
      decoration: BoxDecoration(
        color: bgColor,
        boxShadow: [
          if (showElevation)
            const BoxShadow(
              color: Colors.black12,
              blurRadius: 2,
            )
        ],
      ),
      child: SafeArea(
        child: Container(
          width: double.infinity,
          height: containerHeight,
          alignment: Alignment.center,
          padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 20),
          child: Row(
            mainAxisAlignment: mainAxisAlignment,
            children: items.map((e) {
              var index = items.indexOf(e);
              return GestureDetector(
                onTap: () => onItemSelected(index),
                child: _ItemWidget(
                  iconSize: iconSize,
                  isSelected: index == selectedIndex,
                  item: e,
                  backgroundColor: bgColor,
                  itemCornerRadius: itemCornerRadius,
                  animationDuration: animationDuration,
                  curve: curve,
                ),
              );
            }).toList(),
          ),
        ),
      ),
    );
  }
}

最后的ImteWidget


class _ItemWidget extends StatelessWidget {
  const _ItemWidget(
      {Key? key,
      required this.iconSize,
      required this.isSelected,
      required this.item,
      required this.backgroundColor,
      required this.itemCornerRadius,
      required this.animationDuration,
      this.curve = Curves.linear,
      this.singIcon = false})
      : super(key: key);

  final double iconSize;
  final bool isSelected;
  final BottomBarItem item;
  final Color backgroundColor;
  final double itemCornerRadius;
  final Duration animationDuration;
  final Curve curve;
  final bool singIcon;

  @override
  Widget build(BuildContext context) {
    return Semantics(
      container: true,
      selected: isSelected,
      child: AnimatedContainer(
        height: double.maxFinite,
        duration: animationDuration,
        curve: curve,
        decoration: BoxDecoration(
          color: backgroundColor,
          borderRadius: BorderRadius.circular(itemCornerRadius),
        ),
        child: SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          physics: NeverScrollableScrollPhysics(),
          child: Container(
              padding: EdgeInsets.symmetric(horizontal: 8),
              alignment: Alignment.center,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  _buildIcon(isSelected, item),
                  const SizedBox(
                    height: 2,
                  ),
                  if (!item.singleIcon)
                    Expanded(
                        child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 4),
                      child: DefaultTextStyle.merge(
                          child: item.title,
                          style: _textStyle(isSelected, item)),
                    ))
                ],
              )),
        ),
      ),
    );
  }

  TextStyle _textStyle(bool isSelected, BottomBarItem item) {
    ///返回文字样式
    if (isSelected) {
      return TextStyle(
          color: item.activeColor, fontSize: 12);
    } else {
      return TextStyle(
          color: item.inactiveColor,
          fontSize: 12);
    }
  }

  Widget _buildIcon(bool isSelected, BottomBarItem item) {
    ///根据选中的state,返回不同的icon
    if (isSelected) {
      return Expanded(child: item.activeIcon);
    } else {
      return Expanded(child: item.icon);
    }
  }
}

完整的BottomNavigatorBar

///作者  : Pig Huitao
///时间  : 2022/1/6
///邮箱  : pig.huitao@gmail.com
class BottomNavigatorBar extends StatelessWidget {
  const BottomNavigatorBar(
      {Key? key,
      this.selectedIndex = 0,
      this.iconSize = 24,
      this.backgroundColor,
      this.showElevation = true,
      this.animationDuration = const Duration(milliseconds: 270),
      required this.items,
      required this.onItemSelected,
      this.mainAxisAlignment = MainAxisAlignment.spaceBetween,
      this.itemCornerRadius = 50,
      this.containerHeight = 56,
      this.curve = Curves.linear,
      this.singleIcon = false})
      : super(key: key);

  final int selectedIndex;
  final double iconSize;
  final Color? backgroundColor;
  final bool showElevation;
  final Duration animationDuration;
  final List<BottomBarItem> items;
  final ValueChanged<int> onItemSelected;
  final MainAxisAlignment mainAxisAlignment;
  final double itemCornerRadius;
  final double containerHeight;
  final Curve curve;
  final bool singleIcon;

  @override
  Widget build(BuildContext context) {
    final bgColor = backgroundColor ?? Theme.of(context).bottomAppBarColor;
    return Container(
      decoration: BoxDecoration(
        color: bgColor,
        boxShadow: [
          if (showElevation)
            const BoxShadow(
              color: Colors.black12,
              blurRadius: 2,
            )
        ],
      ),
      child: SafeArea(
        child: Container(
          width: double.infinity,
          height: containerHeight,
          alignment: Alignment.center,
          padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 20),
          child: Row(
            mainAxisAlignment: mainAxisAlignment,
            children: items.map((e) {
              var index = items.indexOf(e);
              return GestureDetector(
                onTap: () => onItemSelected(index),
                child: _ItemWidget(
                  iconSize: iconSize,
                  isSelected: index == selectedIndex,
                  item: e,
                  backgroundColor: bgColor,
                  itemCornerRadius: itemCornerRadius,
                  animationDuration: animationDuration,
                  curve: curve,
                ),
              );
            }).toList(),
          ),
        ),
      ),
    );
  }
}

class _ItemWidget extends StatelessWidget {
  const _ItemWidget(
      {Key? key,
      required this.iconSize,
      required this.isSelected,
      required this.item,
      required this.backgroundColor,
      required this.itemCornerRadius,
      required this.animationDuration,
      this.curve = Curves.linear,
      this.singIcon = false})
      : super(key: key);

  final double iconSize;
  final bool isSelected;
  final BottomBarItem item;
  final Color backgroundColor;
  final double itemCornerRadius;
  final Duration animationDuration;
  final Curve curve;
  final bool singIcon;

  @override
  Widget build(BuildContext context) {
    return Semantics(
      container: true,
      selected: isSelected,
      child: AnimatedContainer(
        height: double.maxFinite,
        duration: animationDuration,
        curve: curve,
        decoration: BoxDecoration(
          color: backgroundColor,
          borderRadius: BorderRadius.circular(itemCornerRadius),
        ),
        child: SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          physics: NeverScrollableScrollPhysics(),
          child: Container(
              padding: EdgeInsets.symmetric(horizontal: 8),
              alignment: Alignment.center,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  _buildIcon(isSelected, item),
                  const SizedBox(
                    height: 2,
                  ),
                  if (!item.singleIcon)
                    Expanded(
                        child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 4),
                      child: DefaultTextStyle.merge(
                          child: item.title,
                          style: _textStyle(isSelected, item)),
                    ))
                ],
              )),
        ),
      ),
    );
  }

  TextStyle _textStyle(bool isSelected, BottomBarItem item) {
    ///返回文字样式
    if (isSelected) {
      return TextStyle(
          color: item.activeColor, fontSize: 12);
    } else {
      return TextStyle(
          color: item.inactiveColor,
          fontSize: 12);
    }
  }

  Widget _buildIcon(bool isSelected, BottomBarItem item) {
    ///根据选中的state,返回不同的icon
    if (isSelected) {
      return Expanded(child: item.activeIcon);
    } else {
      return Expanded(child: item.icon);
    }
  }
}

class BottomBarItem {
  BottomBarItem(
      {required this.icon,
      required this.activeIcon,
      required this.title,
      this.activeColor = Colors.blue,
      this.inactiveColor,
      this.textAlign = TextAlign.center,
      this.singleIcon = false});

  final Widget icon;///未选中的状态
  final Widget activeIcon;///选中的状态
  final Widget title;///标题
  final Color activeColor;///选中的颜色
  final Color? inactiveColor;///未选中的颜色
  final TextAlign textAlign;
  final bool singleIcon;///是否只包含icon
}

使用

///作者  : Pig Huitao
///时间  : 2022/1/5
///邮箱  : pig.huitao@gmail.com

class MainPage extends StatefulWidget {
const  MainPage({Key? key}):super(key: key);
  @override
  _MainPage createState() => _MainPage();
}

class _MainPage extends State<MainPage>
    with SingleTickerProviderStateMixin {
  int _currentIndex = 0;
  final _inactiveColor = Colors.grey;
  final _activeColor = Colors.blue;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('自定义底部导航'),
      ),
      body: getBody(),
      bottomNavigationBar: _buildBottomBar(),
    );
  }

  Widget _buildBottomBar() {
    return BottomNavigatorBar(
      containerHeight: 55,
      backgroundColor: Colors.white,
      selectedIndex: _currentIndex,
      showElevation: true,
      itemCornerRadius: 24,
      curve: Curves.easeIn,
      onItemSelected: (index) => setState(() => _currentIndex = index),
      items: <BottomBarItem>[
        BottomBarItem(
          icon: const Image(
            image: AssetImage('assets/images/icon_home_unselected.png'),
            fit: BoxFit.fill,
          ),
          activeIcon: const Image(
            image: AssetImage('assets/images/icon_home_selected.png'),
            fit: BoxFit.fill,
          ),
          title: const Text('首页'),
          activeColor: Colors.blue,
          inactiveColor: _inactiveColor,
          textAlign: TextAlign.center,
        ),
        BottomBarItem(
          icon: const Image(
            image: AssetImage('assets/images/icon_circle_unselected.png'),
            fit: BoxFit.fill,
          ),
          activeIcon: const Image(
            image: AssetImage('assets/images/icon_circle_selected.png'),
            fit: BoxFit.fill,
          ),
          title: const Text('圈子'),
          activeColor: _activeColor,
          inactiveColor: _inactiveColor,
          textAlign: TextAlign.center,
        ),
        BottomBarItem(
            icon: const Image(
              width: 60,
              height: 38,
              image: AssetImage('assets/images/icon_publish.png'),
              fit: BoxFit.fill,
            ),
            activeIcon: const Image(
              width: 60,
              height: 38,
              image: AssetImage('assets/images/icon_publish.png'),
              fit: BoxFit.fill,
            ),
            title: const Text(
              '发布 ',
            ),
            activeColor: _activeColor,
            inactiveColor: _inactiveColor,
            textAlign: TextAlign.center,
            singleIcon: true),
        BottomBarItem(
          icon: const Image(
            image: AssetImage('assets/images/icon_message_unselected.png'),
            fit: BoxFit.fill,
          ),
          activeIcon: const Image(
            image: AssetImage('assets/images/icon_message_selected.png'),
            fit: BoxFit.fill,
          ),
          title: const Text('消息'),
          activeColor: _activeColor,
          inactiveColor: _inactiveColor,
          textAlign: TextAlign.center,
        ),
        BottomBarItem(
          icon: const Image(
            image: AssetImage("assets/images/icon_me_unselected.png"),
            fit: BoxFit.fill,
          ),
          activeIcon: const Image(
            image: AssetImage("assets/images/icon_me_selected.png"),
            fit: BoxFit.fill,
          ),
          title: const Text('我的'),
          activeColor: Colors.blue,
          inactiveColor: _inactiveColor,
          textAlign: TextAlign.center,
        ),
      ],
    );
  }

  Widget getBody() {
    List<Widget> pages = [
      Container(
        alignment: Alignment.center,
        child: const Text(
          "Home",
          style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
        ),
      ),
      Container(
        alignment: Alignment.center,
        child: const Text(
          "Circles",
          style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
        ),
      ),
      Container(
        alignment: Alignment.center,
        child: const Text(
          "Publishes",
          style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
        ),
      ),
      Container(
        alignment: Alignment.center,
        child: const Text(
          "Messages",
          style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
        ),
      ),
      Container(
        alignment: Alignment.center,
        child: const Text(
          "Users",
          style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
        ),
      ),
    ];
    return IndexedStack(
      index: _currentIndex,
      children: pages,
    );
  }
}

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

推荐阅读更多精彩内容