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

如何为商品标题中的价格单独设置不同颜色?尝试RichText效果不佳

解决商品标题中价格部分单独设色的问题

核心思路

通过拆分文本段+自定义样式实现,你用RichText效果不佳大概率是文本拆分逻辑有误或样式设置冲突,以下是具体实现方案(以Flutter场景为例):

步骤1:拆分标题文本

用正则匹配提取价格片段,将整个标题拆分为「普通文本」和「价格文本」两个部分集合。

步骤2:构建带样式的TextSpan数组

给价格片段单独设置颜色、字号等样式,普通文本用默认样式,最后将所有TextSpan组合起来。

完整代码示例

String productTitle = "XX品牌纯棉T恤夏季新款宽松透气男士上衣 99.00元 包邮";
// 适配多数价格格式的正则(可根据实际需求调整,比如支持¥、$等符号)
RegExp priceRegex = RegExp(r'(\d+\.\d+[元¥$]|\d+[元¥$]|\$\d+\.\d+|\$\d+)');

List<TextSpan> textSpans = [];
int currentPos = 0;

// 遍历所有匹配到的价格
for (Match match in priceRegex.allMatches(productTitle)) {
  // 添加价格前的普通文本
  if (match.start > currentPos) {
    textSpans.add(TextSpan(
      text: productTitle.substring(currentPos, match.start),
      style: TextStyle(color: Colors.black87, fontSize: 14),
    ));
  }
  // 添加带特殊样式的价格文本
  textSpans.add(TextSpan(
    text: match.group(0),
    style: TextStyle(color: Colors.redAccent, fontSize: 16, fontWeight: FontWeight.w600),
  ));
  currentPos = match.end;
}

// 添加剩余的普通文本
if (currentPos < productTitle.length) {
  textSpans.add(TextSpan(
    text: productTitle.substring(currentPos),
    style: TextStyle(color: Colors.black87, fontSize: 14),
  ));
}

// 用更轻量的Text.rich展示(列表场景优先,性能优于RichText)
Text.rich(
  TextSpan(children: textSpans),
  softWrap: true,
  textAlign: TextAlign.left,
)

常见问题排查

  1. 正则匹配失效:根据实际价格格式调整正则规则,比如价格带「¥」就保留正则里的[元¥$],若只有纯数字则简化规则。
  2. 样式被覆盖:确保每个TextSpan都显式设置style,避免父Widget的默认样式干扰价格部分的颜色。
  3. 长文本渲染问题:开启softWrap: true并设置合适的maxLines,避免文本溢出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:46:42