Flutter UI Widget介绍—bottomNavigationBar

本文介绍了如何在Flutter应用中使用BottomNavigationBar实现底部导航,包括设置Icon和label、选中项高亮、页面跳转以及setState的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

BottomNavigationBar用于在App页面的底部添加导航栏。具体用法让我们一起来看代码吧。主要记住这几点:
 
  • BottomNavigationBarItem里面设置Icon和label。
  • currentIndex会使选中的图标高亮。
  • 要使用户选中该图标时自动跳转页面, 需要在BottomNavigationBar里面设置点击事件onTap(),其中的setState可以实现状态的变化。
  • 注意body里面要设置为pages[index]。
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Row Widget Demo',
        theme: ThemeData(
          colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
          useMaterial3: true,
        ),
        home: const MyHomePage(title: 'Flutter Demo')
    );
  }
}

  class MyHomePage extends StatefulWidget {
      const MyHomePage({super.key, required this.title});
      final String title;
      @override
      State<MyHomePage> createState() => _MyHomePageState();
  }

class _MyHomePageState extends State<MyHomePage> {
  List<Widget> pages = [const Page1(), const Page2(), const Page3()];
  int selectedIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('title'),
      ),
      body: pages[selectedIndex],
      bottomNavigationBar: BottomNavigationBar(
       // type: BottomNavigationBarType.shifting,
        backgroundColor: Colors.blue,
        currentIndex: selectedIndex,
        elevation: 200,
        onTap: (index){
          setState(() {
            selectedIndex = index;
          });
        },
        items: const [
          BottomNavigationBarItem(
              icon: Icon(Icons.ac_unit),
              label: 'page1',
              backgroundColor: Colors.red
          ),
          BottomNavigationBarItem(icon: Icon(Icons.add_call), label: 'page2'),
          BottomNavigationBarItem(icon: Icon(Icons.access_time), label: 'page3')
        ],
      ),
    );
  }
}

class Page1 extends StatelessWidget{
  const Page1({super.key});

  @override
  Widget build(BuildContext context) {
    return const Center(child: Text('page1'),);
  }
}

class Page2 extends StatelessWidget{
  const Page2({super.key});

  @override
  Widget build(BuildContext context) {
    return const Center(child: Text('page2'),);
  }
}

class Page3 extends StatelessWidget{
  const Page3({super.key});

  @override
  Widget build(BuildContext context) {
    return const Center(child: Text('page3'),);
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值