12. 底部导航栏

1. 底部导航栏

底部导航栏,是每个APP必备的组件,今天就来实现整个功能,当点击选项的时候,可以切换上面的页面

2. 主页
class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: "底部导航栏",
      home: BottomNavigationWidget(),
    );
  }

}
3. 底部导航栏
class BottomNavigationWidget extends StatefulWidget {

  const BottomNavigationWidget({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _BottomNavigationWidget();
  }
}

class _BottomNavigationWidget extends State<BottomNavigationWidget> {
  final bottomNavigationColor = Colors.blue;

  int currentIndex = 0;

  List<Widget> pagesList = List.empty(growable: true);

  @override
  void initState() {
    pagesList
      ..add(HomeScreen())
      ..add(EmailScreen())
      ..add(PagesScreen())
      ..add(AirplayScreen());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: pagesList[currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(
              icon: Icon(
                Icons.home,
                color: bottomNavigationColor,
              ),
              title:
                  Text("Home", style: TextStyle(color: bottomNavigationColor))),
          BottomNavigationBarItem(
              icon: Icon(
                Icons.email,
                color: bottomNavigationColor,
              ),
              title: Text("Email",
                  style: TextStyle(color: bottomNavigationColor))),
          BottomNavigationBarItem(
              icon: Icon(
                Icons.pages,
                color: bottomNavigationColor,
              ),
              title: Text("Pages",
                  style: TextStyle(color: bottomNavigationColor))),
          BottomNavigationBarItem(
              icon: Icon(
                Icons.airplay,
                color: bottomNavigationColor,
              ),
              title: Text("Airplay",
                  style: TextStyle(color: bottomNavigationColor))),
        ],
        currentIndex: currentIndex,
        onTap: (int index) {
          setState(() {
            currentIndex = index;
          });
        },
      ),
    );
  }
}
4. 上面切换的页面
class HomeScreen extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Home"),
      ),
      body: const Center(
        child: Text("Home"),
      ),
    );
  }

}

推荐阅读更多精彩内容