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

w80xi6nr  于 5个月前  发布在  Flutter
关注(0)|答案(7)|浏览(73)

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

Text("some long string")

字符串
现在,我想设置一个颜色只为**长'*。
有人能告诉我如何编程吗?
范例:
我是长的,一个很长很长的字符串在一些变量中,很长的一个
现在,我想把单词 *

pu82cl6c

pu82cl6c1#

将单词括在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!'),
    ],
  ),
)

字符串
或者使用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)),
    ],
  ),
)

vltsax25

vltsax252#

这是我的代码。

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);
  }
}

字符串

sgtfey8w

sgtfey8w3#

zhpoo出色的answer基础上进行扩展,这里有一个小部件片段,允许您使用正则表达式(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);
  }
}

字符串

yhived7q

yhived7q4#

我最近开发了一个叫做动态文本突出显示的软件包,它可以让你在给定的文本中突出显示一些给定的单词。
查看https://pub.dev/packages/dynamic_text_highlighting

示例

Widget buildDTH(String text, List<String> highlights) {
  return DynamicTextHighlighting(
    text: text,
    highlights: highlights,
    color: Colors.yellow,
    style: TextStyle(
      fontSize: 18.0,
      fontStyle: FontStyle.italic,
    ),
    caseSensitive: false,
  );
}

字符串
它是一个无状态的小部件,所以要进行任何更改,只需调用setState(() {...})

void applyChanges(List<String> newHighlights) {
  setState(() {
    highlights = newHighlights;
  });
}

ql3eal8s

ql3eal8s5#

使用此代码它甚至会突出显示查询字母,检查一次

List<TextSpan> highlight(
      String main, String query) {
    List<TextSpan> children = [];
    List<String> abc = query.toLowerCase().split("");
    for (int i = 0; i < main.length; i++) {
      if (abc.contains(main[i])) {
        children.add(TextSpan(
            text: main[i],
            style: TextStyle(
                backgroundColor: Colors.yellow[300],
                color: Colors.black,
                decoration: TextDecoration.none,
                fontFamily: fontName,
                fontWeight: FontWeight.bold,
                fontSize: 16)));
      } else {
        children.add(TextSpan(
            text: main[i],
            style: TextStyle(
                color: Colors.black,
                decoration: TextDecoration.none,
                fontFamily: fontName,
                fontWeight: FontWeight.w300,
                fontSize: 16)));
      }
    }
    return children;
  }

字符串

hrirmatl

hrirmatl6#

要实现这一点,有几种可能性:
1-使用**Text.rich构造函数而不是Text**小部件,然后在构造函数内部,您将使用TextSpan小部件,这些小部件将允许您通过 style 属性添加样式。第一个TextSpan直接在Text.rich中,然后通过其children属性在第一个TextSpan中添加另一个TextSpan。

Text.rich( 
  TextSpan(
    text: 'Some ', 
    children: <TextSpan>[
      TextSpan(
        text: ' Long ',
        style: TextStyle(fontWeight: FontWeight.bold , background: Paint()..color = Colors.red)),
      TextSpan(
        text: ' world',
        style: TextStyle(backgroundColor: Colors.yellow)),
              ],
            ),
          )

字符串
输出量:


的数据
2-RichText小部件的使用。与Text.rich相同,但这次第一个TextSpan将放在RichText小部件的 text 属性上。

RichText( 
  text:TextSpan(
     text: 'Some ', 
     style: TextStyle(color: Colors.blue), 
     children: <TextSpan>[
        TextSpan(
           text: ' Long ',
           style: TextStyle(color:Colors.black ,fontWeight: FontWeight.bold , background: Paint()..color = Colors.red)),
        TextSpan(
           text: ' world',
           style: TextStyle(backgroundColor: Colors.yellow)),
              ],
            ),
          )


输出量:



3-使用外部包。我建议你highlight_textsubstring_highlight

7dl7o3gd

7dl7o3gd7#

你可以使用这个flutter插件Highlight Text plugin。这是一个很好的选择尝试

相关问题