Flutter:如何在调用TextFormField中的onChanged方法之前调用函数



我有一个可重复使用的TextFormField小部件,用于十进制数字输入。如果用户输入的十进制数字是逗号而不是句点,我想替换它。为此,我创建了一个可重复使用的TextFormField Widget,我想在onChanged方法之前用句点替换逗号。但是,在调用onChanged之前,如何调用函数replaceCommaWithDot((?这是可重复使用的小工具:

class DecimalTextFormField extends StatelessWidget {
const DecimalTextFormField({Key? key, this.onChanged})
: super(key: key);
final ValueChanged? onChanged;
@override
Widget build(BuildContext context) {
replaceCommaWithDot(String inputNumber) {
if (inputNumber.contains(',')) {
String newText = inputNumber.replaceAll(',', '.');
return newText;
}
return inputNumber;
}
return TextFormField(
keyboardType: const TextInputType.numberWithOptions(decimal: true),
// how to use replaceCommaWithDot method when onChanged gets called?
onChanged: onChanged,
);
}
}

如果您只想要结果(不需要ui更新(,那么您的代码片段将正常工作。

onChanged: (value) {
final v = replaceCommaWithDot(value);
if (onChanged != null) onChanged!(v);
},

如果您也想更新UI,可以使用inputFormatters


class CustomFormater extends TextInputFormatter {
replaceCommaWithDot(String inputNumber) {
if (inputNumber.contains(',')) {
String newText = inputNumber.replaceAll(',', '.');
return newText;
}
return inputNumber;
}
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
return newValue.copyWith(text: replaceCommaWithDot(newValue.text));
}
}

DecimalTextFormField将返回

return TextFormField(
keyboardType: const TextInputType.numberWithOptions(decimal: true),
// how to use replaceCommaWithDot method when onChanged gets called?
inputFormatters: [
CustomFormater(),
],
onChanged: (value) {
if (onChanged != null) onChanged!(value);
},
);

有关TextInputFormatter的详细信息。

您应该更好地使用RegEx。在TextFormFieldinputFormatters中添加一个禁止逗号的表达式。它不会取代它,但你就是写不出来。

最新更新