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

Flutter中Text组件行高大于1.0时能否设置每行的垂直对齐?

Flutter Text组件自定义行高垂直对齐问题解决

问题说明

Figma中设置的文本行高(如1.5)直接应用到Flutter TextStyle的height属性后,会出现所有文本行默认底部对齐的问题,即使用Center或Align组件包裹也无法修正,文本行始终保持底部垂直对齐。

示例复现代码:

Text(
  'Example\nExample',
  textAlign: TextAlign.center,
  style:TextStyle(
    height: 2.5,
    fontSize: 20,
  ),
);

可行解决方案

通过Container内边距配合Baseline组件可实现和Figma一致的文本垂直居中效果,代码实现如下:

final text = 'Example Example\nExample Example';
const double height = 2.5;
const double textSize = 16.0;
const double bottomPadding = (height * textSize - textSize) / 2;
const double baseline = height * textSize - height * textSize / 4;
final Widget textWidget = Container(
  color: const Color(0xFFFFFFFF),
  padding: const EdgeInsets.only(bottom: bottomPadding),
  child: Baseline(
    baselineType: TextBaseline.alphabetic,
    baseline: baseline,
    child: Text(
      text,
      style: TextStyle(
        height: height,
        fontSize: textSize,
        color: const Color(0xFFaa3a3a),
      ),
    ),
  ),
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 09:57:03