Skip to content

Instantly share code, notes, and snippets.

@pskink
Created February 5, 2020 11:27
Show Gist options
  • Save pskink/3d2fb8674e3f4f99df63e2b66d9ef8ec to your computer and use it in GitHub Desktop.
Save pskink/3d2fb8674e3f4f99df63e2b66d9ef8ec to your computer and use it in GitHub Desktop.
class FruitColorizer extends TextEditingController {
final Map<String, TextStyle> mapping;
final Pattern pattern;
FruitColorizer(this.mapping)
: pattern = RegExp(mapping.keys.map((key) => RegExp.escape(key)).join('|'));
FruitColorizer.fromColors(Map<String, Color> colorMap)
: this(colorMap.map((text, color) => MapEntry(text, TextStyle(color: color))));
@override
TextSpan buildTextSpan({TextStyle style, bool withComposing}) {
List<InlineSpan> children = [];
// splitMapJoin is a bit tricky here but i found it very handy for populating children list
text.splitMapJoin(pattern,
onMatch: (Match match) {
children.add(TextSpan(text: match[0], style: style.merge(mapping[match[0]])));
},
onNonMatch: (String text) {
children.add(TextSpan(text: text, style: style));
},
);
return TextSpan(style: style, children: children);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment