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

Flutter如何在字符串中嵌入颜色/样式而非仅通过Text组件

可行解决思路

方法一:使用RichText组件(原生支持,无需额外依赖)

Flutter的Text组件仅支持统一样式,要实现局部文本的颜色、粗细定制,最直接的方案是用RichText。它通过TextSpan组合多个不同样式的文本片段,完全适配AlertDialog的使用场景。

示例代码:

AlertDialog(
  content: RichText(
    text: TextSpan(
      style: TextStyle(color: Colors.black, fontSize: 16), // 主体文本默认样式
      children: [
        TextSpan(text: "这是普通黑色文本,"),
        TextSpan(
          text: "这段是红色加粗文本",
          style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold),
        ),
        TextSpan(text: "\r\n这是换行后的普通文本"),
      ],
    ),
  ),
  actions: [TextButton(onPressed: () {}, child: Text("确定"))],
);

方法二:使用flutter_html包(适配HTML格式文本)

如果你的文本是带HTML标签的格式(比如你尝试的<b>Text</b>这类标记),可以借助flutter_html包解析渲染:

  1. 先在pubspec.yaml添加依赖:
dependencies:
  flutter_html: ^3.0.0-beta.2 # 请使用最新版本
  1. 示例代码:
import 'package:flutter_html/flutter_html.dart';

AlertDialog(
  content: Html(
    data: "这是普通黑色文本,<b><span style='color:red;'>这段是红色加粗文本</span></b><br>这是换行后的文本",
    style: {
      "body": Style(color: Colors.black, fontSize: FontSize(16)),
    },
  ),
  actions: [TextButton(onPressed: () {}, child: Text("确定"))],
);

补充说明

  • 你之前用\r\n实现换行的方式,在RichText中同样有效,直接写入TextSpan的文本内容即可。
  • 若只是简单的局部样式需求,优先用RichText,无需引入额外依赖,性能更优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 22:13:13