我有一个TextFormField,用户应在其中输入以下格式的字符串:
XX-XX-XX
反正在用户键入内容时自动添加“-”吗?
谢谢
答案 0 :(得分:0)
这应该对您有用。
class _MyHomePageState extends State<MyHomePage> {
TextEditingController _controller = new TextEditingController();
@override
void initState() {
// TODO: implement initState
super.initState();
// you can have different listner functions if you wish
_controller.addListener(onChange);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
child: Center(
child: TextFormField(
controller: _controller,
),
),
),
);
}
String newText = '';
void onChange(){
String text = _controller.text;
if(text.length < newText.length) { // handling backspace in keyboard
newText = text;
}else if (text.isNotEmpty && text != newText) { // handling typing new characters.
String tempText = text.replaceAll("-", "");
if(tempText.length % 2 == 0){
//do your text transforming
newText = '$text-';
_controller.text = newText;
_controller.selection = new TextSelection(
baseOffset: newText.length,
extentOffset: newText.length
);
}
}
}
}