无法在 Flutter 中扩展 TextField?

mik*_*uth 3 flutter

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

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

此外,当设置expands: true为 TextField 的参数时,小部件会正确扩展以填充该区域。为 EditableText 设置相同的属性时,没有任何反应。不知道为什么。

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

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

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

psk*_*ink 8

使用以下控制器:

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

将其用作:

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

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

编辑

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

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

并使用它:

controller: FruitColorizer.fromColors({
  'apple': Colors.green,
  'orange': Colors.orange,
}),
Run Code Online (Sandbox Code Playgroud)