小编典典

无法在Flutter中扩展TextField?

flutter

我正在尝试修改文本字段,以便可以为同一文本字段中的特定单词设置不同的颜色。例如,“我想要一个苹果”,单词“ apple”应为绿色,其余文本应为黑色。

有用于富文本编辑器的库(例如zefyr,extended_text_field),但我还找到了AnnotatedEditableText的示例。我喜欢上一个解决方案(AnnotatedEditableText),但我想使用TextField获得更丰富的功能,主要是无法在只读可编辑文本中使用的文本选择。

同样,当设置expands: true为TextField的参数时,小部件可以正确展开以填充该区域。为EditableText设置相同的属性时,什么也不会发生。不知道为什么。

所以-
我想将TextField与AnnotatedEditableText小部件一起使用。我可以在不复制粘贴整个TextField类的情况下完成此操作吗?这是我收集的:

  • _TextFieldState是私有的,不能扩展,但是EditableTextState不是私有的,因此可以扩展窗口小部件。
  • TextField小部件不支持EditableText小部件的自定义实现。

有任何想法吗?为什么_TextFieldState是私有的,但EditableTextState不是私有的?


阅读 637

收藏
2020-08-13

共1个答案

小编典典

使用以下控制器:

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]),
  }),
),

并输入TextField:“我吃了两个苹果,一个香蕉和三个橙子”

编辑

如果只想使用颜色,则可以添加命名构造函数:

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

并像这样使用它:

controller: FruitColorizer.fromColors({
  'apple': Colors.green,
  'orange': Colors.orange,
}),
2020-08-13