Flutter完全开发手册
  • Flutter BottomNavigationBar底部导航条

    BottomNavigationBar是属于 Scaffold 中的一个位于底部的控件,这和我们 iOS 中的 tabbar 很像,可以切换不同的模块。BottomNavigationBar通常是和 BottomNavigationBarItem 配合一起使用的。

    BottomNavigationBar 常见的属性

    属性名说明
    itemsList 底部导航条按钮集合(页面集合)
    iconSizeicon
    currentIndex默认选中第几个(页面)
    onTap选中变化回调函数(点击后专跳指定页面)
    fixedColor选中的颜色
    typeBottomNavigationBarType.fixed
    BottomNavigationBarType.shifting

    使用过程中几点需要注意的:

    1、BottomNavigationBar用在Scaffold组件下

    2、当底部导航页面超过三个时,必须要添加type属性(BottomNavigationBarType.fixed),否则的话底部导航会全白,看不到效果

    3、items中是一个BottomNavigationBarItem的集合,里面包含图片及文字标签,在视频教程中给的文字使用的是title属性,我在使用时提示被弃用,用烂了替换title

    我们以微信的框架作为例子,现在让我们去一起实现一下吧

    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);
    
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return const MaterialApp(
          home:  MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      const MyHomePage({Key? key}) : super(key: key);
    
      @override
      State createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State {
      int  _currentIndex = 1;
    
      @override
      Widget build(BuildContext context) {
        // TODO: implement build
        return Scaffold(
    
          appBar: AppBar(
            title: Text("微信"),
          ),
            bottomNavigationBar: BottomNavigationBar(
              currentIndex: _currentIndex,
              //BottomNavigationBar 的点击事件
              onTap: (flag) {
                print("flag = $flag");
                setState(() {
                  _currentIndex = flag;
                });
              },
              fixedColor: Colors.green,
              type: BottomNavigationBarType.fixed,
              items: [
                BottomNavigationBarItem(
                  icon: Image.asset(
                    'images/tabbar_chat.png',
                    height: 20,
                    width: 20,
                  ),
                  activeIcon: Image.asset(
                    'images/tabbar_chat_hl.png',
                    height: 20,
                    width: 20,
                  ),
                  label: ('微信'),
                ),
                const BottomNavigationBarItem(
                    icon: Icon(Icons.bookmark), label: ('通讯录')),
                const BottomNavigationBarItem(icon: Icon(Icons.history), label: ('发现')),
                const BottomNavigationBarItem(
                    icon: Icon(Icons.person_outline), label: ('我')),
              ],
    
    
            )
    
        );
      }
    }
    

    4、currentIndex是BottomNavigationBar 中的属性,是为底部导航页面编的号,从零开始

    5、 我们要改变页面时在onTap中获取点击页面的编号