perhaps someone has encountered such a problem, I need to configure textformfield so that the text is entered in the form in the format / so that the user does not have to type / himself, it seems like you need to use inputformatter, but I can't figure out how to do it
CodePudding user response:
maskformatter.dart
class MaskedTextInputFormatter extends TextInputFormatter {
final String? mask;
final String? separator;
MaskedTextInputFormatter({
@required this.mask,
@required this.separator,
}) {
assert(mask != null);
assert(separator != null);
}
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
if (newValue.text.isNotEmpty) {
if (newValue.text.length > oldValue.text.length) {
if (newValue.text.length > mask!.length) return oldValue;
if (newValue.text.length < mask!.length &&
mask![newValue.text.length - 1] == separator) {
return TextEditingValue(
text:
'${oldValue.text}$separator${newValue.text.substring(newValue.text.length - 1)}',
selection: TextSelection.collapsed(
offset: newValue.selection.end 1,
),
);
}
}
}
return newValue;
}
in textfield use :-
inputFormatter: [
MaskedTextInputFormatter(
mask: '****-****-****-****',
separator: '-',
),
]
CodePudding user response:
I think you are looking for mask text. Try this package mask_text
var maskFormatter = new MaskTextInputFormatter(
mask: ' # (###) ###-##-##',
filter: { "#": RegExp(r'[0-9]') },
type: MaskAutoCompletionType.lazy
);
And assign it to the textfield
TextField(inputFormatters: [maskFormatter])