Flutter Text Field allow user to insertion of a number within a given range only

Viewed 584

I would to force the insertion of only values between 1-20. if user enter 2 it's okay but if user enter 1 after 2 (21) then Text Field will not allow to enter 1 after 2. Is there any RegExp for it.

I tried like this but it's only allow for numbers

inputFormatters: [FilteringTextInputFormatter.allow(RegExp('[1-9,.,:]'))],
1 Answers

Try below code hope its help to you. in below code if you put more than 20 value the cursor takes the first position.

Create one class and declare it minimum and maximum value.

class LimitRange extends TextInputFormatter {
  LimitRange(
    this.minRange,
    this.maxRange,
  ) : assert(
          minRange < maxRange,
        );

  final int minRange;
  final int maxRange;

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    var value = int.parse(newValue.text);
    if (value < minRange) {
      print('value print in between 1 - 20');
      return TextEditingValue(text: minRange.toString());
    } else if (value > maxRange) {
      print('not more 20');
      return TextEditingValue(text: maxRange.toString());
    }
    return newValue;
  }
}

Your Widget:

TextField(
   keyboardType: TextInputType.number,
   inputFormatters: [
             LengthLimitingTextInputFormatter(2),
             LimitRange(1, 20),
         ],
), 

              
Related