Not possible to extend TextField in Flutter?

with the following controller:

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

use it as:

TextField(
  style: TextStyle(fontSize: 32),
  controller: FruitColorizer({
    'apple': TextStyle(color: Colors.green, decoration: TextDecoration.underline),
    'orange': TextStyle(color: Colors.orange, shadows: kElevationToShadow[2]),
  }),
),

and type in your TextField: “i have eaten two apples, one banana and three oranges”

EDIT

if you want to use just colors you can add the named constructor:

FruitColorizer.fromColors(Map<String, Color> colorMap)
: this(colorMap.map((text, color) => MapEntry(text, TextStyle(color: color))));

and use it like:

controller: FruitColorizer.fromColors({
  'apple': Colors.green,
  'orange': Colors.orange,
}),

Leave a Comment