Flutter如何让图标完全居中于圆形按钮内?
Flutter圆形按钮图标未居中问题解决
我实现了一个带边框和阴影的圆形按钮,但图标无法完全居中,尝试过Stack、Positioned、内外边距等方法都没用,代码如下:
Container( height: 55, width: 55, decoration: const BoxDecoration( shape: BoxShape.circle, border: Border.symmetric( horizontal: BorderSide( color: Colors.black, width: 2.0, style: BorderStyle.solid, ), vertical: BorderSide( color: Colors.black, width: 2.0, style: BorderStyle.solid, ), ), boxShadow: [ BoxShadow( color: Colors.black, offset: Offset(3.5, 3.5), blurRadius: 0, spreadRadius: -1, ), ]), child: OutlinedButton( onPressed: () { _controller.forward(); widget.onPress(); }, style: const ButtonStyle( alignment: Alignment.centerLeft, // 问题根源 backgroundColor: MaterialStatePropertyAll(Colors.white), shape: MaterialStatePropertyAll(CircleBorder()), ), child: const Icon( Icons.view_carousel_outlined, size: 35, color: Colors.black, ), ), ),
问题根源
你在OutlinedButton的ButtonStyle里设置了alignment: Alignment.centerLeft,这个属性会强制按钮内部的子组件(图标)向左对齐,这就是图标无法居中的核心原因,和其他布局组件无关。
修复方案
直接移除alignment: Alignment.centerLeft,或者将其改为Alignment.center——因为ButtonStyle默认的对齐方式就是居中,所以移除这个属性即可:
Container( height: 55, width: 55, decoration: const BoxDecoration( shape: BoxShape.circle, border: Border.symmetric( horizontal: BorderSide( color: Colors.black, width: 2.0, style: BorderStyle.solid, ), vertical: BorderSide( color: Colors.black, width: 2.0, style: BorderStyle.solid, ), ), boxShadow: [ BoxShadow( color: Colors.black, offset: Offset(3.5, 3.5), blurRadius: 0, spreadRadius: -1, ), ]), child: OutlinedButton( onPressed: () { _controller.forward(); widget.onPress(); }, style: const ButtonStyle( // 移除或修改alignment属性 backgroundColor: MaterialStatePropertyAll(Colors.white), shape: MaterialStatePropertyAll(CircleBorder()), ), child: const Icon( Icons.view_carousel_outlined, size: 35, color: Colors.black, ), ), ),
额外优化建议
- 外层Container已经设置了边框和阴影,内部的
OutlinedButton可以换成TextButton(不需要默认边框),进一步简化代码 Border.symmetric可以简化为Border.all(color: Colors.black, width: 2.0),因为水平和垂直边框样式完全一致,效果相同
内容的提问来源于stack exchange,提问作者drexvo
相关产品推荐
相关产品推荐

