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

Flutter:如何调整Text组件中TextDecoration下划线与文本的间距?

Flutter 文本下划线与文本间距调整方案

Flutter 默认的 TextStyle 中没有直接属性可以调整 TextDecoration.underline 生成的下划线与文本之间的距离。不过可以通过以下几种实用方式实现自定义间距的下划线:

方法一:用 Stack 叠加文本与自定义下划线

通过 Stack 将文本和独立的下划线容器叠加,手动控制下划线的位置来调整间距:

Stack(
  alignment: Alignment.bottomLeft,
  children: [
    Text(
      'Example',
      style: TextStyle(
        color: Colors.black,
        fontSize: 15,
        fontWeight: FontWeight.bold,
      ),
    ),
    // 自定义下划线,通过bottom值控制与文本的间距
    Positioned(
      bottom: 2, // 数值越大,下划线离文本越远
      left: 0,
      right: 0,
      child: Container(
        height: 1, // 下划线的厚度
        color: Colors.black,
      ),
    ),
  ],
)

方法二:用 RichText 结合 WidgetSpan 实现

利用 RichText 嵌套带有 Padding 的 WidgetSpan,灵活控制下划线的位置和样式:

RichText(
  text: TextSpan(
    children: [
      TextSpan(
        text: 'Example',
        style: TextStyle(
          color: Colors.black,
          fontSize: 15,
          fontWeight: FontWeight.bold,
        ),
      ),
      WidgetSpan(
        alignment: PlaceholderAlignment.bottom,
        child: Padding(
          padding: EdgeInsets.only(bottom: 4), // 调整下划线与文本的垂直间距
          child: Container(
            width: 60, // 下划线宽度,可根据文本长度适配
            height: 1,
            color: Colors.black,
          ),
        ),
      ),
    ],
  ),
)

方法三:封装自定义 Text 组件(进阶)

如果项目中需要多次使用带自定义间距下划线的文本,可以封装一个自定义组件,把下划线逻辑整合进去,方便全局复用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:30:53