基本上,我想实现“标签”功能。我很难做出一个逻辑,其中如果文本包含“#”(例如,我喜欢#flutter),则#flutter文本会将其颜色更改为蓝色。
您能给我一个关于要使用哪个小部件的提示,或者是否有用于此的软件包?
我似乎找不到类似的问题。
希望这行得通!
Widget _getColoredHashtagText(String text) {
if (text.contains('#')) {
var preHashtag = text.substring(0, text.indexOf('#'));
var postHashtag = text.substring(text.indexOf('#'));
var hashTag = postHashtag;
var other;
if (postHashtag.contains(' ')) {
hashTag = postHashtag.substring(0, postHashtag.indexOf(' '));
other = postHashtag.substring(postHashtag.indexOf(' '));
}
return RichText(
text: TextSpan(
style: DefaultTextStyle.of(context).style,
children: <TextSpan>[
TextSpan(text: preHashtag),
TextSpan(text: hashTag, style: TextStyle(color: Colors.blue)),
TextSpan(text: other != null ? other : ""),
],
),
);
} else {
return Text(text);
}
}
使用RichText
,您可以创建具有不同样式的文本,其中每个文本都是TextSpan
,如下所示:
RichText(
text: TextSpan(
children: [
TextSpan(text: "I love "),
TextSpan(text: "#flutter", style: TextStyle(color: Colors.blue)),
],
),
)
[您可以使用String
并创建文本和主题标签的列表,然后映射该列表以进行检查:如果元素包含#
,则使用蓝色的TextSpan
,否则使用默认的TextSpan
。] >
这是一个快速的示例,您可以尝试对其进行改进:
RichText _convertHashtag(String text) {
List<String> split = text.split(RegExp("#"));
List<String> hashtags = split.getRange(1, split.length).fold([], (t, e) {
var texts = e.split(" ");
if (texts.length > 1) {
return List.from(t)
..addAll(["#${texts.first}", "${e.substring(texts.first.length)}"]);
}
return List.from(t)..add("#${texts.first}");
});
return RichText(
text: TextSpan(
children: [TextSpan(text: split.first)]..addAll(hashtags
.map((text) => text.contains("#")
? TextSpan(text: text, style: TextStyle(color: Colors.blue))
: TextSpan(text: text))
.toList()),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.indigo,
appBar: AppBar(title: Text('#hashtag')),
body: Center(
child: _convertHashtag("I love #flutter and #android very much"),
),
);
}