Not possible to extend TextField in Flutter?

前端 未结 1 890
闹比i
闹比i 2020-12-10 20:26

I\'m trying to modify a text field so that I can set different colors to specific words in the same text field. For example \"I want an apple\" and the word \"apple\" should

相关标签:
1条回答
  • 2020-12-10 21:04

    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,
    }),
    
    0 讨论(0)
提交回复
热议问题