You need to enable JavaScript to run this app. 如何在Flutter的Text.rich()组件中实现文本居中对齐
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter的Text.rich()组件中实现文本居中对齐

实现方案

TextSpan 本身不提供对齐配置项,文本对齐是外层Text组件的控制属性,你只需为Text.rich添加textAlign参数即可实现居中效果。
如果添加后仍未居中,说明当前Text组件的宽度仅包裹了文本内容,没有撑满父容器,可配合外层容器让Text占满父宽度即可。

修改后代码示例

Text.rich(
  textAlign: TextAlign.center, // 新增这一行即可实现文本居中
  TextSpan(
    text: "Go to your e-mail inbox and ",
    style: TextStyle(
        color: appBackground_color,
        fontSize: 14,
        fontWeight: FontWeight.w500),
    children: <InlineSpan>[
      TextSpan(
        text: "activate your account",
        style: TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.w700,
          color: appBackground_color,
        ),
      ),
      TextSpan(
        text: " to proceed.",
        style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
            color: appBackground_color),
      ),
    ],
  ),
)

特殊场景适配

如果需要文本在整个父容器水平居中,可在外层嵌套Center组件,或者给Text套一个宽度为父容器最大宽度的容器:

// 外层套Center的示例
Center(
  child: Text.rich(
    textAlign: TextAlign.center,
    // 其余TextSpan代码保持不变
  ),
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 08:21:02