使用 flutter 实现一个底部导航栏

现现在打开一个 App,好比微信、支付宝,都能看到一个底部导航栏,用来切换到不一样的展现页。今天就用 Flutter 实现一下这种效果。html


在 Flutter 里,基本上全部的东西都是组件。Flutter 也已经有了现成的底部导航栏组件了 -- BottomNavigationBar,因此用 Flutter 实现底部导航,实际上是很简单地一件事情,只须要知道怎么使用就行了。git

  1. 首先,利用 IDE 实现代码大体的结构
import 'package:flutter/material.dart';

class BottomNav extends StatefulWidget {
  @override
  _BottomNavState createState() => _BottomNavState();
}

class _BottomNavState extends State<BottomNav> {
  @override
  Widget build(BuildContext context) {
    return Container(

    );
  }
}
复制代码

笔者用的是 vs code,而后有安装 flutter 、dart 的插件。要实现上述的结构,只要在编辑器中输入 stful,而后就会有提示出来了,如图所示: github

vs code 编辑器会 dart 的支持是十分友好的了,也有不少提示,在编码时能够充分利用。目前惟一的缺点应该就是缺乏 flutter inspector 了。微信

  1. 实现_BottomNavState 的 build 方法
class _BottomNavState extends State<BottomNav> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Bottom Navigation Demo')),
      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
          BottomNavigationBarItem(icon: Icon(Icons.business), title: Text('Business')),
          BottomNavigationBarItem(icon: Icon(Icons.school), title: Text('School')),
        ],
        fixedColor: Colors.green,
        currentIndex: 0,
        onTap: (int idx) {}
      ),
    );
  }
}
复制代码

这时候,用仿真器看到的效果以下: app

  1. 添加交互

到这里,咱们已经实现了大概的效果,可是你会发现,点击底部的图标切换,是没有效果的。如今,就给底部导航添加交互行为。编辑器

  • 定义变量_currentIndex,并将 BottomNavagationBar 的 currentIndex 的值用变量 _currentIndex 代替
int _currentIndex = 0;
复制代码
  • 实现 BottomNavagationBar 的 onTap 方法
void onItemTapped(int idx) {
  setState(() {
    _currentIndex = idx;
  })
}
复制代码

至此,就完成了底部导航栏的功能啦。ide

完成代码请看这里 bottom_navagation_bar.dart学习

最后

笔者最近在学习flutter,会持续地记录本身的学习过程,并放在 github 上。ui

有问题欢迎提出,你们一块儿讨论,一块儿进步。编码

参考资料

BottomNavigationBar class

相关文章
相关标签/搜索