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

Flutter中如何为Text组件字符串的特定字符设置不同颜色

解决方案

要实现数字黑色、运算符红色的效果,你可以用RichText组件替代Text,它支持为不同文本片段设置独立样式,同时保持inputstring的String类型不变。

修改后的完整代码

import 'package:flutter/material.dart';

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key);

  String inputstring = '79+93-27';

  // 拆分字符串并生成带样式的TextSpan列表
  List<TextSpan> _buildStyledTextSpans(String input) {
    // 正则匹配连续数字或单个运算符
    final pattern = RegExp(r'(\d+|[+\-*/])');
    final matches = pattern.allMatches(input);
    
    return matches.map((match) {
      final segment = match.group(0)!;
      // 判断当前片段是否为运算符
      final isOperator = ['+', '-', '*', '/'].contains(segment);
      return TextSpan(
        text: segment,
        style: TextStyle(
          fontSize: 30,
          color: isOperator ? Colors.red : Colors.black,
        ),
      );
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: RichText(
            text: TextSpan(
              children: _buildStyledTextSpans(inputstring),
            ),
          ),
        ),
      ),
    );
  }
}

关键说明

  • 使用正则表达式r'(\d+|[+\-*/])'将输入字符串拆分为连续数字段和单个运算符,避免多位数被拆成单个数字字符
  • 通过_buildStyledTextSpans方法遍历拆分后的片段,为运算符设置红色,数字设置黑色
  • 保留inputstring的String类型,完全符合你的需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 18:41:06