实现的方式

​ 因为Flutter的widget分为StatelessWidget和StatefulWidget.我们使用底部导航栏肯定是通过点击底部的导航按钮来实现页面的更改,所以包含BottomNavigationBar的Widget必须是一个StatefulWidget.

​ 因为Scaffold这个widget中默认对BottomNavigationBar支持.所以直接用Scaffold就可以了.

效果图

\"在这里插入图片描述\"

直接贴代码

class BottomNavigationWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => BottomNavigationWidgetState();
}

class BottomNavigationWidgetState extends State<BottomNavigationWidget> {
  final _bottomNavigationColor = primaryColor;
  int _currentIndex = 0;
  List<Widget> bodyList = List();

  @override
  void initState() {
    super.initState();
    bodyList
      ..add(HomeScreen())
      ..add(DiscoverScreen())
      ..add(WorldScreen())
      ..add(MineScreen());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: bodyList[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.home, color: _bottomNavigationColor),
             : Text(
              \'主页\',
              style: _bottomNavigationTextStyle(),
            ),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.camera, color: _bottomNavigationColor),
             : Text(
              \'发现\',
              style: _bottomNavigationTextStyle(),
            ),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.language, color: _bottomNavigationColor),
             : Text(
              \'世界\',
              style: _bottomNavigationTextStyle(),
            ),
          ),
          BottomNavigationBarItem(
            icon: Icon(
              Icons.supervised_user_circle,
              color: _bottomNavigationColor,
            ),
             : Text(
              \'我的\',
              style: _bottomNavigationTextStyle(),
            ),
          ),
        ],
        currentIndex: _currentIndex,
        onTap: (int index) {
          setState(() {
            _currentIndex = index;
          });
        },
        type: BottomNavigationBarType.fixed,
      ),
    );
  }

  //底部导航栏的样式
  TextStyle _bottomNavigationTextStyle() => TextStyle(color: primaryColor);
}
收藏 打印