Flutter - BottomNavigationBar

今天我们来讲下底部导航栏BottomNavigationBar,它也是在Scaffold的脚手架当中。

        bottomNavigationBar: BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          fixedColor: Colors.greenAccent,
          items: [
            BottomNavigationBarItem(
                icon: Icon(Icons.explore), title: Text('Explore')),
            BottomNavigationBarItem(
                icon: Icon(Icons.smoke_free), title: Text('SmokeFree')),
            BottomNavigationBarItem(
                icon: Icon(Icons.list), title: Text('List')),
            BottomNavigationBarItem(
                icon: Icon(Icons.person), title: Text('My')),
          ],
        ),
  • BottomNavigationBar 底部导航栏组件
  • BottomNavigationBarItem 每一个item显示的按钮
  • type 当底部导航栏超过默认大小后,显示就会不见了,这时候需要加上type类型,让它自适应。
  • fixedColor 指的是被选中的导航栏的颜色
    显示如图:
    nav.png

现在我们来点下面按钮,发现点击了没啥用,切换不了激活的按钮。
它是由currentIndex控制的。下来我们来修改下代码。
因为这个底部导航栏是动态的,所以我们这次要用的组件应该继承于StatefulWidget。

class  extends StatefulWidget {
  @override
  _State createState() => _State();
}

class _State extends State<> {
  @override
  Widget build(BuildContext context) {
    return Container(
      
    );
  }
}

上面是有状态Widget的基本格式。第一个类是用来控制状态组件状态的,第二个类就是我们的自定义组件。下来我们修改下代码:

class BottomNavigationBarDemo extends StatefulWidget {
  @override
  _BottomNavigationBarDemoState createState() =>
      _BottomNavigationBarDemoState();
}

class _BottomNavigationBarDemoState extends State {
  int _currentIndex = 0;  // 当前导航栏索引

  void _onTapHandler(int index) {   // 定义一个_onTapHandler来设置索引
    setState(() {     // 设置状态的方法
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return BottomNavigationBar(
      currentIndex: _currentIndex,  // 当前索引值
      onTap: _onTapHandler,  // 点击事件,来设置索引
      type: BottomNavigationBarType.fixed,
      fixedColor: Colors.greenAccent,
      items: [
        BottomNavigationBarItem(
            icon: Icon(Icons.explore), title: Text('Explore')),
        BottomNavigationBarItem(
            icon: Icon(Icons.smoke_free), title: Text('SmokeFree')),
        BottomNavigationBarItem(icon: Icon(Icons.list), title: Text('List')),
        BottomNavigationBarItem(icon: Icon(Icons.person), title: Text('My')),
      ],
    );
  }
}

在上面代码里已经添加了注释,大家可以自己看看。
最后将Scaffold里的bottomNavigationBar设置成BottomNavigationBarDemo()类调用就行啦。

你可能感兴趣的:(Flutter - BottomNavigationBar)