问题:
Flutter 中 TextField 根据文字改变颜色
例如 “I want an apple” , “apple” 就自动变为蓝色。
解决方法:
继承TextEditingController
来实现:
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('|')); @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); } }
使用时,就可以根据关键字自定义颜色:
TextField( style: TextStyle(fontSize: 32), controller: FruitColorizer({ 'apple': TextStyle(color: Colors.green, decoration: TextDecoration.underline), 'orange': TextStyle(color: Colors.orange, shadows: kElevationToShadow[2]), }), ),