flutter 利用浮动按钮,实现导航栏中间放置圆形按钮效果

水深无声 2021-07-25 02:45 826阅读 0赞
  1. 思路:
  2. Scaffold中设置浮动按钮->外包Container设置宽高来控制按钮大小->
  3. 利用浮动按钮的位置参数floatingActionButtonLocation设置值为centerDocked
  4. 定位到底部导航栏的中心靠上->设置外包容器的圆角和背景色实现按钮的边框效果
  5. ->利用按钮大小和margin等布局遮盖掉导航栏中心原来的图标->在事件中根据导航栏索引来设置页面导航

代码示例:

  1. import "package:flutter/material.dart";
  2. import 'page/1.dart';
  3. import 'page/2.dart';
  4. import 'page/3.dart';
  5. import 'page/routes.dart';
  6. void main()
  7. {
  8. runApp(App());
  9. }
  10. class App extends StatelessWidget{
  11. @override
  12. Widget build(BuildContext context) {
  13. // TODO: implement build
  14. return MaterialApp(
  15. //去掉右上角的debug贴纸
  16. debugShowCheckedModeBanner: false,
  17. home:Tabs(),
  18. //默认路由
  19. initialRoute:'/me' ,
  20. //路由跳转参数配置
  21. onGenerateRoute:routeInfo
  22. );
  23. }
  24. }
  25. class Tabs extends StatefulWidget {
  26. final index;
  27. Tabs({ Key key,this.index=0}) : super(key: key);
  28. @override
  29. _TabsState createState() => _TabsState(index:this.index);
  30. }
  31. class _TabsState extends State<Tabs> {
  32. int index=0;
  33. _TabsState({ this.index=0});
  34. List _page=[Home3(),Home2(),Home4()];
  35. @override
  36. Widget build(BuildContext context) {
  37. return Scaffold(appBar: AppBar(title: Text("hh")),
  38. //浮动按钮
  39. floatingActionButton: Container(
  40. child: FloatingActionButton(
  41. child: Icon(Icons.add),
  42. //事件导航
  43. onPressed: (){ setState(() {
  44. this.index=1;
  45. });},
  46. backgroundColor: this.index==1? Colors.red:Colors.yellow
  47. ),
  48. height: 60,
  49. width: 60,
  50. padding: EdgeInsets.all(8),
  51. margin: EdgeInsets.only(top:10),
  52. decoration: BoxDecoration(
  53. borderRadius: BorderRadius.circular(40),
  54. color: Colors.blue
  55. ),
  56. ),
  57. //设置按钮位置
  58. floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
  59. body:_page[this.index],
  60. bottomNavigationBar: BottomNavigationBar(
  61. items:[
  62. BottomNavigationBarItem(//单个bar内容
  63. icon:Icon(Icons.home),
  64. title:Text("首页"),
  65. ),
  66. BottomNavigationBarItem(
  67. icon:Icon(Icons.category),
  68. title:Text("第二页"),
  69. ),
  70. BottomNavigationBarItem(
  71. icon:Icon(Icons.category),
  72. title:Text("第三页"),
  73. )
  74. ],
  75. currentIndex: this.index, //选中的底部bar索引
  76. fixedColor: Colors.green, //选中的颜色
  77. onTap:(index){ setState(() {
  78. this.index=index;
  79. });}, //点击bar回调,必须传入index参数,bar的索引
  80. ),
  81. );
  82. }
  83. }
  84. class Home extends StatelessWidget {
  85. const Home({ Key key}) : super(key: key);
  86. @override
  87. Widget build(BuildContext context) {
  88. return Container(
  89. child: Column(
  90. children: <Widget>[
  91. ],
  92. ),
  93. );
  94. }
  95. }

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

发表评论

表情:
评论列表 (有 0 条评论,826人围观)

还没有评论,来说两句吧...

相关阅读