Created
February 5, 2020 11:27
-
-
Save pskink/3d2fb8674e3f4f99df63e2b66d9ef8ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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