学习笔记
本篇文章是基于上篇文章的:https://blog.csdn.net/convex1009848621/article/details/127803176?spm=1001.2014.3001.5501
上篇文章我们创建了一个底部有3个tab的并且可以切换的页面。
在本篇文章,我们再进行扩展,将底部的tab增加到5个,并将中间的tab按钮,设置成特殊样式。
1.创建5个tab的底部栏
import 'package:first_flutter_app/pages/tabs/add.dart';
import 'package:first_flutter_app/pages/tabs/category.dart';
import 'package:first_flutter_app/pages/tabs/home.dart';
import 'package:first_flutter_app/pages/tabs/mine.dart';
import 'package:first_flutter_app/pages/tabs/search.dart';
import 'package:flutter/material.dart';
class Tabs extends StatefulWidget {
const Tabs({Key? key}) : super(key: key);
_TabsState createState() => _TabsState();
}
class _TabsState extends State<Tabs> {
int _currentIndex = 0;
List<Widget> _pages = [
HomePage(),
CategoryPage(),
AddPage(),
SearchPage(),
MinePage()
];
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("flutter demo"),
),
body: _pages[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: "首页"),
BottomNavigationBarItem(icon: Icon(Icons.category), label: "分类"),
BottomNavigationBarItem(icon: Icon(Icons.add), label: "发布"),
BottomNavigationBarItem(icon: Icon(Icons.search), label: "发现"),
BottomNavigationBarItem(icon: Icon(Icons.person), label: "我的"),
],
),
);
}
}
显示效果
2.引入FloatingActionButton
在Scaffold添加
floatingActionButton: FloatingActionButton(
onPressed: () {},
),
得到毫无修饰的浮动按钮
来做一些修饰
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {},
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
直接看效果
基本上就实现了我们想要的样式
3.设置点击事件
现在的浮动按钮还没有点击事件,我们想点击浮动按钮的时候要切换到发布页面上
也就是floatingActionButton的onPressed要将_currentIndex设置成2,而且要在setState()中进行赋值
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
setState(() {
_currentIndex = 2;
});
},
),
效果