Flutter 使用 BottomAppBar 自定义底部导航(中间浮出按钮)

Flutter 使用 BottomAppBar 自定义底部导航(中间浮出按钮)_第1张图片
效果图.gif

底部导航 参考

1、普通效果:我们可以通过ScaffoldbottomNavigationBar属性来设置底部导航,通过Material组件库提供的BottomNavigationBarBottomNavigationBarItem两种组件来实现Material风格的底部导航栏。
2、如图效果:Material组件库中提供了一个BottomAppBar组件,它可以和FloatingActionButton配合实现这种“打洞”效果。

实现如图“打洞”效果

底部BottomAppBarchild设置为Row,并且将Row用其children 5 等分,中间的位置空出(我的实现方法)。在Scaffold中设置floatingActionButton,并且设置floatingActionButtonLocationFloatingActionButtonLocation.centerDocked

代码如下:
Scaffold(
      //...省略部分代码
      floatingActionButton: FloatingActionButton(
          //悬浮按钮
          child: Icon(Icons.add),
          onPressed: () {}),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      body: pages[currentIndex],
      bottomNavigationBar: BottomAppBar(
        child: Row(
          children: [
            SizedBox(height: 49, width: itemWidth, child: bottomAppBarItem(0)),
            SizedBox(height: 49, width: itemWidth, child: bottomAppBarItem(1)),
            SizedBox(height: 49, width: itemWidth),
            SizedBox(height: 49, width: itemWidth, child: bottomAppBarItem(2)),
            SizedBox(height: 49, width: itemWidth, child: bottomAppBarItem(3))
          ],
          mainAxisAlignment: MainAxisAlignment.spaceAround,
        ),
        shape: CircularNotchedRectangle(),
      ),
    );

自定义 Item View

上述代码中,其中4个item都是SizedBox(height: 49, width: itemWidth, child: bottomAppBarItem(0))(中间的为空白,itemWidthdouble itemWidth = MediaQuery.of(context).size.width / 5;)。bottomAppBarItem方法,传入底部导航item的index,返回Widget,代码如下:

Widget bottomAppBarItem(int index) {
    //设置默认未选中的状态
    TextStyle style = TextStyle(fontSize: 12, color: Colors.black);
    String imgUrl = normalImgUrls[index];
    if (currentIndex == index) {
      //选中的话
      style = TextStyle(fontSize: 13, color: Colors.blue);
      imgUrl = selectedImgUrls[index];
    }
    //构造返回的Widget
    Widget item = Container(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Image.asset(imgUrl, width: 25, height: 25),
            Text(
              titles[index],
              style: style,
            )
          ],
        ),
        onTap: () {
          if (currentIndex != index) {
            setState(() {
              currentIndex = index;
            });
          }
        },
      ),
    );
    return item;
  }
变量解释

pages 为要显示的每一页Widget;
currentIndex 表示当前选中底部item的index;
titles 底部item显示的文字列表;
normalImgUrls 为未选中状态的图片地址列表;
selectedImgUrls 为选中状态的图片地址列表。

未选中与选中状态

ImageText默认设为未选中图片及样式,判断如果 currentIndex == index 的话,就改为选中状态图片及样式,这样构建item的时候就可以。

点击切换

在每个item的onTap 事件中如果 currentIndex != index(不处理点击当前选中的item的情况) 则 currentIndex = index,调用 setState()重新buildbody: pages[currentIndex]即可显示最新的页面。

Tips

现在虽然实现了简单的效果,但是尚有不足,优化篇了解一下。

你可能感兴趣的:(Flutter 使用 BottomAppBar 自定义底部导航(中间浮出按钮))