Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexanderShniperson/3d949bf721ae46f546e6aacc6402ba2d to your computer and use it in GitHub Desktop.
Save AlexanderShniperson/3d949bf721ae46f546e6aacc6402ba2d to your computer and use it in GitHub Desktop.
Flutter custom price input formatter for standard TextField
import 'package:flutter/services.dart';
class MaxPriceTextInputFormatter extends TextInputFormatter {
MaxPriceTextInputFormatter({this.maxPrice})
: assert(maxPrice == null || maxPrice > 0);
final double maxPrice;
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
if (newValue.text.isEmpty || maxPrice == null) {
return newValue;
}
String value = newValue.text.replaceAll(",", ".");
try {
final priceValue =
double.parse(value.endsWith(".") ? "${value}0" : value);
if (priceValue <= maxPrice) {
String finalString = value;
if (finalString.contains(".")) {
final List<String> components = value.split(".").toList();
if (components.length > 1 && components.last.length > 2) {
components.last = components.last.substring(0, 2);
}
finalString = "${components.first}.${components.last}";
}
return TextEditingValue(
text: finalString,
selection: newValue.selection,
composing: newValue.composing,
);
} else {
return TextEditingValue(
text: "${maxPrice.toInt()}",
selection: newValue.selection,
composing: newValue.composing,
);
}
} catch (ex) {
print(ex.toString());
return oldValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment