首页 > 解决方案 > 只有一个字符的小容器没有正确居中 - Flutter

问题描述

只有一个字符的小容器没有正确居中,有或没有填充设置为 0。

如果我减小字体大小将呈现居中,但默认文本大小没有

Container(
  decoration: BoxDecoration(
    color: Colors.green,
    shape: BoxShape.circle,
  ),
  width: 20.0,
  height: 20.0,
  alignment: Alignment.center,
  padding: EdgeInsets.all(0.0),
  child: Text(
    '+',
  ),
)

绿色容器的结果

更新:使用图标代替字母的行为完全相同。 在此处输入图像描述

如果我将大小从 20 更改为 40: 在此处输入图像描述

代码

Container(
            width: 40,
            height: 40,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: Colors.grey,
            ),
            child: RotatedBox(
              quarterTurns: 3,
              child: Icon(
                Icons.expand_less,
                color: Colors.white,
              ),
            ),
          ),

更新 2:使用 Fitted 与图标一起使用: 在此处输入图像描述

Container(
            width: 20,
            height: 20,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: Theme.of(context).textTheme.caption.color,
            ),
            child: FittedBox(
              child: RotatedBox(
                quarterTurns: 3,
                child: Icon(
                  Icons.expand_less,
                  color: Theme.of(context).primaryColor,
                ),
              ),
            ),
          ),

标签: flutterwidgetcontainerscenter

解决方案


我无法重现这一点。但我假设您的默认字体大小对于容器来说太大了。您可以尝试将 Text 包装在FittedBox中,以便它适应容器:

return Container(
      decoration: BoxDecoration(
        color: Colors.green,
        shape: BoxShape.circle,
      ),
      width: 20.0,
      height: 20.0,
      alignment: Alignment.center,
      padding: EdgeInsets.all(0.0),
      child: FittedBox(
        child:Text('+')
     ),
);

推荐阅读