本节教程将介绍如何添加Flutter底部导航栏的方法,主要用到了Flutter BottomNavigationBar这个组件,底部导航栏几乎是每个移动app必备的设计要求,所有请认真阅读本教程,学会Flutter底部菜单的使用。
首先我们新建一个Flutter App,此过程小编就不介绍了,新建之后项目中会有一个“main.dart”的主文件,我们只需要在extends继承“State”这个类的地方加入如下代码即可:class _MyHomePageState extends State {
//默认选择第一个底部导航菜单(Home)
int _currentIndex = 0;
//List里面为同一个构造方法,这里是同一个界面,只是设置背景颜色不一样,
//你也可以在此处加入不同页面的构造方法,就会加载相应的界面了。
final List _children = [
PlaceholderWidget(Colors.white),
PlaceholderWidget(Colors.deepOrange),
PlaceholderWidget(Colors.green)
];
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: _children[_currentIndex], //body内容颜色随角标值变化
bottomNavigationBar: BottomNavigationBar(
onTap: selectOption, //tap点击事件,会切换菜单选项
currentIndex: _currentIndex,
items: [
BottomNavigationBarItem(
icon: new Icon(Icons.home),
title: new Text('Home'),
),
BottomNavigationBarItem(
icon: new Icon(Icons.mail),
title: new Text('Messages'),
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
title: Text('Profile')
)
],
),
);
}
// 点击底部导航时会进入selectOption方法,并设置当前的currentIndex角标值
void selectOption(int index) {
setState(() {
_currentIndex = index;
});
}
}
从上面的Flutter底部导航实现示例中可以看出,我们还有一个“PlaceholderWidget.dart”的类,我们只需要在“main.dart”主文件中加入如下引用即可:import "PlaceholderWidget.dart";
我们在上方代码的List集合中有三个PlaceholderWidget(xxx)的构造方法,从我们引入的“PlaceholderWidget.dart”头文件可以看出,我们还需要新建一个名为“PlaceholderWidget.dart”的文件,内容代码如下:import 'package:flutter/material.dart';
class PlaceholderWidget extends StatelessWidget {
final Color color;
PlaceholderWidget(this.color);
@override
Widget build(BuildContext context) {
return Container(
color: color,
);
}
}
通过上面的步骤,就可以实现一个Flutter底部导航的应用了,如图:
来源网站:太平洋学习网,转载请注明出处:http://www.tpyyes.com/a/flutter/805.html