Flutter中如何将通知徽标(Badge)叠加在通知图标上
解决AppBar通知图标右上角徽章贴合问题
你当前的问题是因为IconButton和Positioned是actions列表里的两个独立组件,而actions默认是Row布局,导致徽章和图标并排显示而非叠加。要实现徽章贴合在图标右上角,需要把图标和徽章放在同一个Stack容器里,利用Stack的层级布局实现叠加效果。
修改后的代码如下:
: Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).primaryColor, leading: Center( child: SizedBox( height: 40, width: 40, child: ClipRRect( borderRadius: BorderRadius.circular(20), child: Image.asset( 'assets/images/vr_logo.png', fit: BoxFit.cover, height: 10, width: 10, ), )), ), title: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Text( dashboardViewModel.dashboardDetail.data?.garageName ?? "", style: white40017, ), Text( dashboardViewModel.dashboardDetail.data?.garageOwnerName ?? "", style: white50014, ) ], ), actions: [ // 用Stack包裹图标和徽章,实现叠加效果 Stack( children: [ IconButton( icon: const Icon(Icons.notifications_none_sharp), onPressed: () { context.push(const NotificationScreen()); }, ), Positioned( top: 5, right: 5, // 调整该值可让徽章更贴合图标右上角 child: Container( padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), decoration: const BoxDecoration(shape: BoxShape.circle, color: Colors.red), alignment: Alignment.center, child: const Text( "1", style: TextStyle(color: Colors.white, fontSize: 12), // 可选:优化文字显示样式 ), ), ) ], ) ], ), body: SizedBox( height: size(context).height, width: size(context).width, child: Padding( padding: const EdgeInsets.all(15.0), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ trackingTopBar(context), Text( "Overview", style: black60018, ), progressAndJob(context), corsorelSliderBar(context), amountBar(context), customerStatusBar(context) ]), ), ), ));
关键改动说明:
- 将
IconButton与Positioned徽章放入同一个Stack组件,使徽章能叠加在图标上方。 - 调整
Positioned的right参数,让徽章位置更贴合图标右上角,避免超出视觉边界。 - 给徽章内的文字添加基础样式,提升整体显示美观度(可选配置)。
内容的提问来源于stack exchange,提问作者MARSH
相关产品推荐
相关产品推荐

