Last active
July 29, 2020 13:04
-
-
Save AlexanderShniperson/3d949bf721ae46f546e6aacc6402ba2d to your computer and use it in GitHub Desktop.
Flutter custom price input formatter for standard TextField
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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