底部导航栏目前在手机应用中非常常见,可见其对于软件设计来说非常的有必要和重要。下面简单总结使用flutter和dart如何实现底部导航栏的制作。
首先值得注意的是底部导航栏为动态的组件,所以继承的话应该是StatefulWidget类,而不是平常的StatelessWidget。
为了方便测试编写两个简单的页面,分别为home页和person页,页面的代码如下:
home.dart:
1 2 3 4 5 6 7 8 9 10 11
| import 'package:flutter/material.dart';
class Home extends StatelessWidget { @override Widget build(BuildContext context) { return Container( child: new Center( child: new Text("首页"), )); } }
|
person.dart:
1 2 3 4 5 6 7 8 9 10 11
| import 'package:flutter/material.dart';
class Person extends StatelessWidget { @override Widget build(BuildContext context) { return Container( child: new Center( child: new Text("个人页"), )); } }
|
下面开始编写底部导航的代码:
除了继承动态组件之外,还要定义好图标以及相关导航文字,使用list数据结构实现,所有的页面都是类,所以定义类数组来初始化之前完成的home页和person页,特别需要注意的是bottomNavigationBar的类型,即type要为fixed。然后定义相关点击事件,body即为页面数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| class ListAppBar extends StatefulWidget { @override _ListState createState() => _ListState(); }
class _ListState extends State<ListAppBar> {
final List<BottomNavigationBarItem> bottomTabs = [ BottomNavigationBarItem(icon: Icon(CupertinoIcons.home), title: Text("首页")), BottomNavigationBarItem( icon: Icon(CupertinoIcons.person), title: Text("个人")), ];
final List tabPage = [ Home(), Person(), ];
int index = 0; var page; @override void initState() { page = tabPage[index]; super.initState(); }
@override Widget build(BuildContext context) { return new Scaffold( bottomNavigationBar: new BottomNavigationBar( type: BottomNavigationBarType.fixed, iconSize: 22, selectedFontSize: 12, currentIndex: index, items: bottomTabs, onTap: (i) { setState(() { index = i; page = tabPage[i]; }); }, ), body: page, ); } }
|
完成后的截图如下:
个人页
首页