首页 > 解决方案 > 如何在具有圆形边界的容器内居中图标小部件

问题描述

我面临一个问题,最终其他人已经有了解决方案。

我想 Flutter Container 圆形框形状,大小 >=1 的边框和作为子项的 Icon 完美地居中于容器的中间。

然而,Flutter 做了各种奇怪的事情,搞砸了图标的中心位置。对齐中心和中心小部件都没有帮助。

我尝试使用 Stack 和 position 但我认为这不是这样做的方法,因为必须有一种直接的方法来让 Container 中的图标完全居中并强制 Flutter 不要更改图标的大小或添加填充或移位身边的孩子。

这是一个代码片段

if (widget.selected) {
      return Container(
        width: widget.size,
        height: widget.size,
        constraints: BoxConstraints.tightFor(width: widget.size, height: widget.size),
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          border: Border.all(color: Colors.blue, width: 5),
          color: Colors.yellow,
        ),
        alignment: Alignment.center,
        child: Icon(Icons.check_circle, size: widget.size-5, color: Colors.lightGreen),
      );
    }
    else
      return Container(
        width: widget.size,
        height: widget.size,
        constraints: BoxConstraints.tightFor(width: widget.size, height: widget.size),
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          border: Border.all(color: Colors.blue, width: 5),
          color: Colors.transparent,
        ),
      );

在此处输入图像描述

我还检查了小部件树,发现发生了我不想在那里发生的事情。

标签: flutterflutter-layout

解决方案


使用Stack代替 aColumn并将 theIconContainer.

        Stack(
            children: [
              Align(
                alignment: Alignment.center,
                child: Container(
                  height: 100,
                  width: 100,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(color: Colors.blue, width: 5),
                    color: Colors.yellow,
                  ),
                ),
              ),
              Align(
                  alignment: Alignment.center,
                  child: Icon(Icons.check_circle,
                      size: 190, color: Colors.lightGreen)),
            ],
          ),

推荐阅读