如何以编程方式突出显示字符串中的单词

ket*_*iwu 5 dart flutter flutter-layout

有什么办法可以改变字符串中特定单词的颜色?

Text("some long string")
Run Code Online (Sandbox Code Playgroud)

现在我只想给字加颜色。

有人可以告诉我如何编程吗?

例如:-

我是一个很长很长的字符串,包含一些变量,很长

现在在这里我想分开长词。我可以将简单的字符串分开以突出显示一个单词,但不确定如何找到并突出显示每个单词。

zhp*_*poo 10

这是我的代码。

import 'package:flutter/material.dart';

class HighlightText extends StatelessWidget {
  final String text;
  final String highlight;
  final TextStyle style;
  final TextStyle highlightStyle;
  final Color highlightColor;
  final bool ignoreCase;

  HighlightText({
    Key key,
    this.text,
    this.highlight,
    this.style,
    this.highlightColor,
    TextStyle highlightStyle,
    this.ignoreCase: false,
  })  : assert(
          highlightColor == null || highlightStyle == null,
          'highlightColor and highlightStyle cannot be provided at same time.',
        ),
        highlightStyle = highlightStyle ?? style?.copyWith(color: highlightColor) ?? TextStyle(color: highlightColor),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    final text = this.text ?? '';
    if ((highlight?.isEmpty ?? true) || text.isEmpty) {
      return Text(text, style: style);
    }

    var sourceText = ignoreCase ? text.toLowerCase() : text;
    var targetHighlight = ignoreCase ? highlight.toLowerCase() : highlight;

    List<TextSpan> spans = [];
    int start = 0;
    int indexOfHighlight;
    do {
      indexOfHighlight = sourceText.indexOf(targetHighlight, start);
      if (indexOfHighlight < 0) {
        // no highlight
        spans.add(_normalSpan(text.substring(start)));
        break;
      }
      if (indexOfHighlight > start) {
        // normal text before highlight
        spans.add(_normalSpan(text.substring(start, indexOfHighlight)));
      }
      start = indexOfHighlight + highlight.length;
      spans.add(_highlightSpan(text.substring(indexOfHighlight, start)));
    } while (true);

    return Text.rich(TextSpan(children: spans));
  }

  TextSpan _highlightSpan(String content) {
    return TextSpan(text: content, style: highlightStyle);
  }

  TextSpan _normalSpan(String content) {
    return TextSpan(text: content, style: style);
  }
}


Run Code Online (Sandbox Code Playgroud)


小智 10

扩展zhpoo的精彩答案,这里有一个小部件片段,它允许您使用正则表达式(dart 的 RegExp)以编程方式设置字符串中的任何内容的样式/突出显示。

dartpad 演示链接:https://dartpad.dev/d7a0826ed1201f7247fafd9e65979953

class RegexTextHighlight extends StatelessWidget {
  final String text;
  final RegExp highlightRegex;
  final TextStyle highlightStyle;
  final TextStyle nonHighlightStyle;

  const RegexTextHighlight({
    @required this.text,
    @required this.highlightRegex,
    @required this.highlightStyle,
    this.nonHighlightStyle,
  });

  @override
  Widget build(BuildContext context) {
    if (text == null || text.isEmpty) {
      return Text("",
          style: nonHighlightStyle ?? DefaultTextStyle.of(context).style);
    }

    List<TextSpan> spans = [];
    int start = 0;
    while (true) {
      final String highlight =
          highlightRegex.stringMatch(text.substring(start));
      if (highlight == null) {
        // no highlight
        spans.add(_normalSpan(text.substring(start)));
        break;
      }

      final int indexOfHighlight = text.indexOf(highlight, start);

      if (indexOfHighlight == start) {
        // starts with highlight
        spans.add(_highlightSpan(highlight));
        start += highlight.length;
      } else {
        // normal + highlight
        spans.add(_normalSpan(text.substring(start, indexOfHighlight)));
        spans.add(_highlightSpan(highlight));
        start = indexOfHighlight + highlight.length;
      }
    }

    return RichText(
      text: TextSpan(
        style: nonHighlightStyle ?? DefaultTextStyle.of(context).style,
        children: spans,
      ),
    );
  }

  TextSpan _highlightSpan(String content) {
    return TextSpan(text: content, style: highlightStyle);
  }

  TextSpan _normalSpan(String content) {
    return TextSpan(text: content);
  }
}
Run Code Online (Sandbox Code Playgroud)


Gün*_*uer 7

将单词包装在TextSpan中,并分配style属性以更改文本外观,并使用RichText代替Text

RichText(
  text: TextSpan(
    text: 'Hello ',
    style: DefaultTextStyle.of(context).style,
    children: <TextSpan>[
      TextSpan(text: 'bold', style: TextStyle(fontWeight: FontWeight.bold)),
      TextSpan(text: ' world!'),
    ],
  ),
)
Run Code Online (Sandbox Code Playgroud)

或使用Text.rich构造函数https://docs.flutter.io/flutter/widgets/Text-class.html

const Text.rich(
  TextSpan(
    text: 'Hello', // default text style
    children: <TextSpan>[
      TextSpan(text: ' beautiful ', style: TextStyle(fontStyle: FontStyle.italic)),
      TextSpan(text: 'world', style: TextStyle(fontWeight: FontWeight.bold)),
    ],
  ),
)
Run Code Online (Sandbox Code Playgroud)

  • @ketiwu 你可以把它添加到你的 TextStyle `TextStyle(background: Paint()..color = Colors.pink)` 在这里找到它 https://github.com/flutter/flutter/issues/20430 (2认同)