| 1 | import 'package:cake_wallet/generated/i18n.dart'; |
| 2 | import 'package:flutter/services.dart'; |
| 3 | |
| 4 | class DecimalInputFormatter extends TextInputFormatter { |
| 5 | const DecimalInputFormatter({this.maxDecimals = 7}) : assert(maxDecimals >= 0); |
| 6 | |
| 7 | final int maxDecimals; |
| 8 | |
| 9 | @override |
| 10 | TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { |
| 11 | final text = newValue.text; |
| 12 | if (text.isEmpty) return newValue; |
| 13 | |
| 14 | if (S.current.all.startsWith(text)) { |
| 15 | return const TextEditingValue( |
| 16 | text: "", |
| 17 | selection: TextSelection.collapsed(offset: 0), |
| 18 | ); |
| 19 | } |
| 20 | |
| 21 | final regex = maxDecimals == 0 ? RegExp(r'^\d*$') : RegExp('^\\d*([.,]\\d{0,$maxDecimals})?\$'); |
| 22 | return regex.hasMatch(text) ? newValue.copyWith(text: text.replaceAll(',', '.')) : oldValue; |
| 23 | } |
| 24 | } |