Small details that build taste in Flutter.

curated by Kamran BekirovKamran Bekirov

Limit the amount users can type in a field

Some amount fields have a hard limit. Paying with bonus is one: the amount can't go over the bonus balance. The usual way is to let users type anything, then show an error. The better way is a field that never accepts more in the first place:

A small formatter does it. Every edit passes through inputFormatters before it lands in the field, so parse the new text there, and when it goes above the max, return the old value. The edit never happens:

import 'package:flutter/services.dart';
  
class MaxAmountInputFormatter extends TextInputFormatter {
  final double maxAmount;
  
  MaxAmountInputFormatter(this.maxAmount);
  
  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    if (newValue.text.isEmpty) return newValue;
  
    final double? value = double.tryParse(newValue.text);
    if (value == null) return oldValue;
  
    if (value > maxAmount) return oldValue;
  
    return newValue;
  }
}

Two things fall out of this. Empty text passes through, so users can always clear the field and start over. And anything above the max is dropped: the field keeps its old value, no error to show, nothing to dismiss.

Wire it up:

TextField(
  keyboardType: const TextInputType.numberWithOptions(
    decimal: true,
  ),
  inputFormatters: [
    FilteringTextInputFormatter.allow(
      RegExp(r'^\d+\.?\d{0,2}'),
    ),
    MaxAmountInputFormatter(maxAmount),
  ],
)

The filter runs first, so only digits with up to two decimals reach the max check.

The limit itself often comes from two amounts. In the bonus example, users can't spend more bonus than they have, and no more than the order costs. Take the smaller one:

final double maxAmount = min(bonusBalance, orderTotal);
Kamran Bekirov
Kamran Bekirov

Want this level of care in your Flutter apps?

Work With Me