Flutter——BottomNavigationBar实现

BottomNavigationBar 是 Flutter 的一个组件,可以实现底部导航栏的功能,其中 currentIndex 属性为显示页面的序号,由于不同页面显示的 AppBar 和 body 都不同,所以可以根据 currentIndex 的值来动态加载显示的视图。

Demo 实现底部三个导航栏,然后点击后切换不同的 AppBar 和 body

先来效果图:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

下面是代码部分:

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

class _MyHomePageState extends State<MyHomePage> {

  //当前页面索引
  var _currentIndex = 0;

  //当前页面对象,需要自己创建
  HomePage homePage;
  VideoPage videoPage;
  PersonPage personPage;

  //当前页面appBar样式
  getCurrentAppBar() {
    if (_currentIndex == 0) {
      return homeAppBar;
    } else if (_currentIndex == 1) {
      return vedioAppBar;
    } else if (_currentIndex == 2) {
      return personAppBar;
    }
  }

  //当前页面body样式
  getCurrentBoby() {
    if (_currentIndex == 0) {
      //??运算,当homePage为空时将new HomePage()赋值给homePage,否则保持不变
      homePage ??= new HomePage();
      return homePage;
    } else if (_currentIndex == 1) {
      videoPage ??= new VideoPage();
      return videoPage;
    } else if (_currentIndex == 2) {
      personPage ??= new PersonPage();
      return PersonPage();
    }
  }

  //底部导航栏items
  var bottomNavigationBarItems = [
    new BottomNavigationBarItem(
      title: Text(
        '首页',
      ),
      icon: Icon(Icons.home,),
    ),
    new BottomNavigationBarItem(
      title: Text(
        '发现',
      ),
      icon: Icon(Icons.explore,),
    ),
    new BottomNavigationBarItem(
      title: Text(
        '我',
      ),
      icon: Icon(Icons.perm_identity,),
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: getCurrentAppBar(),
      body: getCurrentBoby(),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        items: bottomNavigationBarItems,
        type: BottomNavigationBarType.fixed,
        onTap: ((index) {
          setState(() {
            _currentIndex = index;
          });
        }),
      ),
    );
  }
}

其中各页面的 appbar 的样式如下:

//首页appbar
final Widget homeAppBar = new AppBar(
  title: Text('首页'),
  actions: <Widget>[
    IconButton(
      icon: Icon(Icons.search),
      onPressed: () {
        print("转跳搜索页面");
      },
    ),
  ],
);

//发现页appbar
final Widget vedioAppBar = new AppBar(
  title: Text('视频'),
);

//我的页面appbar
final Widget personAppBar = new AppBar(
  title: Text('我'),
);

其中 AppBar 和 body 部分都是通过函数根据当前页面的索引来加载的,达到点击底部导航栏的不同 item 显示不同页面 。

发布了38 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43851639/article/details/100989592