Flutter实现BottomNavigationBar中图标与标签的垂直居中
要让图标和标签水平排列且垂直居中(替代默认的上下堆叠布局),可以通过自定义BottomNavigationBarItem的内容来实现,具体修改方案如下:
- 给
BottomNavigationBar设置type: BottomNavigationBarType.fixed,保证多个导航项的布局稳定 - 取消默认的
label显示,改为在icon属性中用Row组件包裹图标和文本,通过对齐属性实现垂直居中 - 调整图标与文本的间距、字体大小等样式,匹配视觉需求
修改后的完整代码:
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', debugShowCheckedModeBanner: false, theme: ThemeData(primarySwatch: Colors.blue), home: const MyHomePage(), ); } } class MyHomePage extends StatelessWidget { const MyHomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: Container(), bottomNavigationBar: Container( margin: const EdgeInsets.only(bottom: 15.0, left: 10.0, right: 10.0), decoration: const BoxDecoration( borderRadius: BorderRadius.only( topRight: Radius.circular(30), topLeft: Radius.circular(30), ), boxShadow: [ BoxShadow( color: Colors.black38, spreadRadius: 0, blurRadius: 10, ), ], ), child: ClipRRect( borderRadius: const BorderRadius.all(Radius.circular(30.0)), child: BottomNavigationBar( backgroundColor: Colors.black, fixedColor: Colors.white, unselectedItemColor: Colors.white, type: BottomNavigationBarType.fixed, height: 60, items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Icon( Icons.home_outlined, color: Colors.white, size: 28.0, ), SizedBox(width: 5), Text( 'Home', style: TextStyle(fontSize: 14), ), ], ), label: '', ), BottomNavigationBarItem( icon: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Icon( Icons.shopping_bag_outlined, color: Colors.white, size: 28.0, ), SizedBox(width: 5), Text( 'Cart', style: TextStyle(fontSize: 14), ), ], ), label: '', ), BottomNavigationBarItem( icon: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Icon( Icons.person_outline, color: Colors.white, size: 28.0, ), SizedBox(width: 5), Text( 'Profile', style: TextStyle(fontSize: 14), ), ], ), label: '', ), ], ), ), ), ); } }
关键修改说明:
BottomNavigationBarType.fixed:确保多个导航项均匀分配宽度,避免自适应布局导致的错位- 自定义
icon布局:用Row横向排列图标和文本,通过crossAxisAlignment: CrossAxisAlignment.center实现两者垂直居中对齐 - 隐藏默认
label:将label设为空字符串,避免默认的上下堆叠布局干扰自定义样式 - 调整导航栏高度:设置
height属性适配水平布局的高度需求
内容的提问来源于stack exchange,提问作者Imrul Emon
相关产品推荐
相关产品推荐

