Flutter中FloatingActionButton使用withValues设置透明度异常问题
问题原因与解决方法
问题原因
FloatingActionButton默认自带elevation(阴影效果),当设置半透明背景色时,按钮底层的阴影会透过半透明底色显现出来,视觉上就会呈现浑浊的暗粉色。而AppBar的阴影是在组件下方,与自身背景区域不重叠,因此半透明色显示正常。
另外注意:Colors.red.withValues(alpha: 0.3)是Flutter旧版API,当前推荐使用withOpacity(0.3)或withAlpha((0.3*255).toInt())(alpha值需传入0-255的整数)。
正确实现方式
方案1:移除FloatingActionButton的阴影
通过设置elevation: 0消除阴影,半透明背景色即可正常显示:
actions: [ FloatingActionButton( backgroundColor: Colors.red.withOpacity(0.3), elevation: 0, onPressed: () {}, child: Icon(Icons.add), ) ]
方案2:保留层级但隐藏阴影颜色
如果需要保留FloatingActionButton的点击层级变化,可将阴影颜色设为透明:
actions: [ FloatingActionButton( backgroundColor: Colors.red.withOpacity(0.3), shadowColor: Colors.transparent, onPressed: () {}, child: Icon(Icons.add), ) ]
方案3:替换为IconButton(若无需FAB凸起样式)
AppBar的actions区域更适合使用IconButton,它无默认阴影,半透明色显示正常:
actions: [ IconButton( icon: Icon(Icons.add), style: IconButton.styleFrom( backgroundColor: Colors.red.withOpacity(0.3), iconColor: Colors.white, ), onPressed: () {}, ) ]
内容的提问来源于stack exchange,提问作者user1052610
相关产品推荐
相关产品推荐

