我们应该利用
inputFormatters
而是避免使用更新文本后出现内部循环
TextEditingController
TextFormField(
decoration: InputDecoration(
hintText: 'MM/DD/YYYY',
),
inputFormatters: [
TextInputFormatter.withFunction((oldValue, newValue) {
String newText = newValue.text;
int newTextLength = newText.length;
if (newValue.text.length > oldValue.text.length && (newTextLength == 2 || newTextLength == 5)) {
return TextEditingValue(
text: newText + '/',
selection: TextSelection.fromPosition(TextPosition(offset: newTextLength + 1)));
}
return newValue;
})
])