Reputation: 239
I want to make a feature like the picture, and it needs to limit the count of input value separated by space.
I found many solutions used maxLength, but is not working in this case.
Then I tried another way like
onChanged: (String v) {
// if reach the maximum count
_controller.text = v.substring(0, _text);
},
but the input behavior became weird.
Is there a proper way to do this?
Upvotes: 1
Views: 2723
Reputation: 1
You can extend TextInputFormatter
:
class MaxWordTextInputFormater extends TextInputFormatter {
final int maxWords;
final ValueChanged<int>? currentLength;
MaxWordTextInputFormater({this.maxWords = 1, this.currentLength});
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
int count = 0;
if (newValue.text.isEmpty) {
count = 0;
} else {
count = newValue.text.trim().split(RegexUtil.spaceOrNewLine).length;
}
if (count > maxWords) {
return oldValue;
}
currentLength?.call(count);
return newValue;
}
}
Upvotes: 3
Reputation: 2447
You can consider the following ways.
TextFormField
with a validator
.TextFormField(
validator: (text) {
if (text.split(' ').length > max_limit) {
return 'Reached max words';
}
return null;
},
);
TextField(
controller: _text,
decoration: InputDecoration(
labelText: 'Enter 5 words',
errorText: _validate ? 'You have entered more than 5 words' : null,
),
);
On your OnChanged()
-> update the _validate
variable based on your condition.
Upvotes: 2
Reputation: 46
You can use mask_text_input_formatter, https://pub.dev/packages/mask_text_input_formatter to help you to separate the word format that you want to split
TextField(inputFormatters: [
MaskTextInputFormatter(mask: '+# (###) ###-##-##', filter: { "#": RegExp(r'[0-
9]') });
])
Upvotes: 0