You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中无法将TextButton内的Icon居中问题求助

解决TextButton内图标居中问题

你的问题出在TextButton默认的最小尺寸约束上,默认的minWidth和minHeight会让按钮保持固定大小,即便你设置了padding: 0和alignment: center,也会因为这个约束导致图标偏移。

修改最小化按钮的ButtonStyle,添加constraints属性覆盖默认约束,同时确保按钮尺寸和外层容器匹配:

@override
Widget build(BuildContext context) {
  return Row(
    mainAxisAlignment: MainAxisAlignment.center,
    children: [
      SizedBox(
        height: 25,
        width: 25, // 增加宽度让按钮呈正方形,视觉更协调
        child: TextButton(
          onPressed: appWindow.minimize,
          style: const ButtonStyle(
            alignment: Alignment.center,
            padding: MaterialStatePropertyAll(EdgeInsets.all(0)),
            // 覆盖默认最小尺寸约束,让按钮跟随外层SizedBox的大小
            constraints: MaterialStatePropertyAll(BoxConstraints(
              minWidth: 25,
              minHeight: 25,
            )),
          ),
          child: const Icon(
            Icons.minimize,
            color: Colors.white,
          ),
        ),
      ),
      TextButton(
          onPressed: maximizeOrRestore,
          child: Icon(
            appWindow.isMaximized ? Icons.fullscreen_exit : Icons.fullscreen,
            color: Colors.white,
          )),
      TextButton(
        onPressed: appWindow.close,
        child: const Icon(
          Icons.close,
          color: Colors.white,
        ),
      )
    ],
  );
}

你也可以直接去掉外层SizedBox,把尺寸约束完全放在ButtonStyle里,效果一致:

TextButton(
  onPressed: appWindow.minimize,
  style: const ButtonStyle(
    alignment: Alignment.center,
    padding: MaterialStatePropertyAll(EdgeInsets.all(0)),
    fixedSize: MaterialStatePropertyAll(Size(25, 25)), // 直接设置固定尺寸
  ),
  child: const Icon(
    Icons.minimize,
    color: Colors.white,
  ),
),

修改后图标就能在TextButton内完美居中。

内容的提问来源于stack exchange,提问作者Coinmaster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 10:25:21