Flutter中为GNav底部导航栏添加通知徽章的实现方法
你可以直接利用GButton组件自带的badge属性实现通知徽章效果,以下是适配你代码的实现方案:
静态徽章示例(固定显示数字)
class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return Scaffold( bottomNavigationBar: Container( color: Colors.black, padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), child: GNav( // 移除const,因为badge为动态Widget backgroundColor: Colors.fromARGB(255, 0, 0, 0), color: Color.fromARGB(255, 203, 203, 203), activeColor: Color.fromARGB(255, 255, 255, 255), tabBackgroundColor: Color.fromARGB(55, 255, 255, 255), gap: 8, padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8), tabs: [ GButton( icon: Icons.forum, text: 'Forum', // 自定义通知徽章 badge: Container( padding: EdgeInsets.all(2), decoration: BoxDecoration( color: Colors.red, borderRadius: BorderRadius.circular(10), ), constraints: BoxConstraints( minWidth: 16, minHeight: 16, ), child: Text( '5', style: TextStyle( color: Colors.white, fontSize: 10, fontWeight: FontWeight.bold, ), textAlign: TextAlign.center, ), ), ), GButton( icon: Icons.home, text: 'Home', ), GButton( icon: Icons.calendar_month, text: 'Search', ), ], ), ), ); } }
动态徽章示例(随状态更新数字)
如果需要根据业务逻辑动态调整徽章数字,可以通过State管理实现:
class _HomePageState extends State<HomePage> { int _forumNotifyCount = 3; // 初始通知数量 // 模拟更新通知数的方法 void _updateNotifyCount() { setState(() { _forumNotifyCount += 2; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GNav徽章演示'), actions: [ IconButton(icon: Icons.add_alert, onPressed: _updateNotifyCount) ], ), bottomNavigationBar: Container( color: Colors.black, padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), child: GNav( backgroundColor: Colors.fromARGB(255, 0, 0, 0), color: Color.fromARGB(255, 203, 203, 203), activeColor: Color.fromARGB(255, 255, 255, 255), tabBackgroundColor: Color.fromARGB(55, 255, 255, 255), gap: 8, padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8), tabs: [ GButton( icon: Icons.forum, text: 'Forum', // 通知数为0时隐藏徽章 badge: _forumNotifyCount > 0 ? Container( padding: EdgeInsets.all(2), decoration: BoxDecoration( color: Colors.red, borderRadius: BorderRadius.circular(10), ), constraints: BoxConstraints( minWidth: 16, minHeight: 16, ), child: Text( '$_forumNotifyCount', style: TextStyle( color: Colors.white, fontSize: 10, fontWeight: FontWeight.bold, ), textAlign: TextAlign.center, ), ) : null, ), GButton( icon: Icons.home, text: 'Home', ), GButton( icon: Icons.calendar_month, text: 'Search', ), ], ), ), ); } }
关键说明
- 必须移除
GNav前的const关键字,因为badge是动态Widget,无法使用const修饰 - 通过
Container可自定义徽章的背景色、圆角、内边距和文字样式,完全匹配你需要的视觉效果 - 动态场景下,调用
setState更新通知数即可实现徽章内容的实时变化 - 可通过判断通知数是否大于0,控制徽章的显示或隐藏
内容的提问来源于stack exchange,提问作者richard.online
相关产品推荐
相关产品推荐

