Flutter-使用BottomNavigationBar来实现底部导航栏

在Flutter中,可以使用BottomNavigationBar widget来实现底部导航栏,以下是一个简单的示例代码:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

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

class _MyAppState extends State<MyApp> {
  int _currentIndex = 0;
  final List<Widget> _children = [
    HomePage(),
    MessagesPage(),
    ProfilePage(),
  ];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Bottom Navigation Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        body: _children[_currentIndex],
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _currentIndex,
          onTap: onTabTapped,
          items: [
            BottomNavigationBarItem(
              icon: new Icon(Icons.home),
              title: new Text('Home'),
            ),
            BottomNavigationBarItem(
              icon: new Icon(Icons.message),
              title: new Text('Messages'),
            ),
            BottomNavigationBarItem(
              icon: new Icon(Icons.person),
              title: new Text('Profile'),
            ),
          ],
        ),
      ),
    );
  }

  void onTabTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.blue,
      child: Center(
        child: Text('Home Page', style: TextStyle(fontSize: 32)),
      ),
    );
  }
}

class MessagesPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.green,
      child: Center(
        child: Text('Messages Page', style: TextStyle(fontSize: 32)),
      ),
    );
  }
}

class ProfilePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.yellow,
      child: Center(
        child: Text('Profile Page', style: TextStyle(fontSize: 32)),
      ),
    );
  }
}

在这个示例中,定义了一个有3个页面的底部导航栏,分别是"Home"、“Messages"和"Profile”。在MyAppbuild方法中,创建了一个Scaffold,它包含一个BottomNavigationBar和一个body,根据当前选中的_currentIndex来显示相应的页面。

BottomNavigationBar中,设置currentIndex属性,它指定了当前选中的页面,以及items属性,它是一个包含3个BottomNavigationBarItem的列表,每个条目包含一个图标和一个标题。

定义一个onTabTapped方法,当用户点击底部导航栏的某个按钮时,会调用此方法,在此方法中更新_currentIndex的值,然后调用setState方法来重建底部导航栏。

最后,定义3个简单的页面HomePage、MessagesPage和ProfilePage,它们分别显示一个文本,用于表示当前处于哪个页面。

猜你喜欢

转载自blog.csdn.net/m0_48259951/article/details/129666975