测试反馈输入框不允许输入特殊字符,于是我就想怎么处理,慢慢写下了以下代码
final MyInputFormatter _inputFormatter = MyInputFormatter();
// ...
Container(
child: TextField(
controller: insAccountController,
inputFormatters: [_inputFormatter],
),
),
class MyInputFormatter extends FilteringTextInputFormatter {
MyInputFormatter() : super.allow(RegExp(r'^[a-zA-Z0-9_.]+$'));
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
final filteredText =
newValue.text.replaceAll(RegExp(r'[^a-zA-Z0-9_.]+'), '');
if (filteredText != newValue.text) {
return TextEditingValue(
text: filteredText,
selection: TextSelection.collapsed(offset: filteredText.length),
);
}
return newValue;
}
}