[英]Changing the text characters as user is typing in textfield flutter
我是 flutter 的新手,我正在尝试找出一种方法,以便用户可以在我的应用程序中以非常具体的方式输入他们的代词。 例如,他们可以键入“she/her/hers”,如果按空格键,则会出现“/”。 我目前有一个文本字段,但我不确定从哪里开始以及它如何工作。
我现在在我的代码中有这个:
String _textSelect(String _controller) {
_controller = _controller.replaceAll(" ", "/");
return str;
}
但它不起作用。 任何帮助将非常感激。 谢谢!
我建议为此使用 TextInputFormatter。
看看https://api.flutter.dev/flutter/services/TextInputFormatter-class.html
“要创建自定义格式化程序,请扩展 TextInputFormatter class 并实现 formatEditUpdate 方法。”
您可以通过传入接受新文本作为参数的 function 来使用文本字段的onChanged
属性。 尝试这个:
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _textController = TextEditingController();
@override
void dispose() {
_textController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: TextField(
controller: _textController,
onChanged: (text) {
_textController.text = text.replaceAll(" ", "/");
_textController.value = _textController.value.copyWith(
selection:
TextSelection(baseOffset: text.length, extentOffset: text.length),
composing: TextRange.empty,
);
}
),
),
),
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.