flutter - flutter : How to change color of all text before a particular character in TextField?

标签 flutter textfield flutter-widget

我正在尝试在 Flutter 应用程序中创建一个 TextField 小部件,其中我希望允许用户插入如下文本字符串:

USER-0123456789

其中文本USER(“-”字符之前的所有文本)应为红色,其他应为黑色。

现在的问题是我不知道有什么方法可以做到这一点。经过一些研究,我发现我可以通过使用 RichText Widget 使用普通的 Text Widget 来完成此操作。但是,我不知道 TextField Widget 有任何类似的小部件。请帮助我摆脱这种困境。

最佳答案

我能够按照 pskink 的建议使用 if 语句创建两个 TextSpan 来解决问题。

MyTextController 类:

class MyTextController extends TextEditingController {
  @override
  TextSpan buildTextSpan({TextStyle style, bool withComposing}) {
    List<InlineSpan> children = [];
    if(text.contains('-')){
      children.add(TextSpan(style: TextStyle(color: Colors.redAccent), text: text.substring(0, text.indexOf('-'))));
      children.add(TextSpan(text: text.substring(text.indexOf('-'))));
    } else {
      children.add(TextSpan(style: TextStyle(color: Colors.redAccent), text: text));
    }
    return TextSpan(style: style, children: children);
  }
}

TextFormField中的用法:

TextFormField(
    keyboardType: TextInputType.text,
    controller: MyTextController(),
),

有关光标错位错误的更新: 我无法找到此错误的解决方案。如果我在不久的将来找到它,我会在这里更新。我所做的就是隐藏光标本身,这样就不会被注意到。

关于flutter - flutter : How to change color of all text before a particular character in TextField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60352633/

相关文章:

ios - 在没有 Xcode 的情况下,在 Flutter 中将 GoogleService-Info.plist 保存在哪里?

flutter - 使用勇敢的浏览器调试flutter web app

flutter - Flutter Dismissible Widget在关闭后重新显示该小部件

flutter - 如何在flutter中禁用Cupertinopicker?

flutter - 如何在没有 firebase 或一个信号的情况下用 flutter 从后端推送通知?

dart - 在 Flutter 中向卡片添加新列

ios - 如何使 if 语句更改 xcode 中的文本字段?

Flutter TextField 值总是大写和去抖动

android - Android 上的 libgdx 文本字段语言