Ank*_*ush 2 textfield flutter flutter-widget
我正在尝试在 Flutter App 中创建一个 TextField 小部件,我想在其中允许用户插入这样的文本字符串:
USER-0123456789
其中文本USER(' - ' 字符之前的所有文本)应为红色,其他应为黑色。
现在的问题是我不知道有什么方法可以做到这一点。经过一番研究,我发现我可以通过使用 RichText Widget 来使用普通的 Text Widget 来完成此操作。但是,我不知道 TextField 小部件有任何类似的小部件。请帮助我摆脱这种情况。
我能够按照 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);
}
}
Run Code Online (Sandbox Code Playgroud)
在TextFormField 中的用法:
TextFormField(
keyboardType: TextInputType.text,
controller: MyTextController(),
),
Run Code Online (Sandbox Code Playgroud)
关于光标错位错误的更新: 我无法找到此错误的解决方案。如果我在不久的将来找到它,我会在这里更新。我所做的是,将光标本身隐藏起来,这样就不会被注意到。
| 归档时间: |
|
| 查看次数: |
1008 次 |
| 最近记录: |