56 lines
1.5 KiB
Dart
56 lines
1.5 KiB
Dart
import 'package:flutter/services.dart';
|
|
|
|
class FrequencyInputFormatter extends TextInputFormatter {
|
|
@override
|
|
TextEditingValue formatEditUpdate(
|
|
TextEditingValue oldValue,
|
|
TextEditingValue newValue,
|
|
) {
|
|
// Skip formatting if deleting
|
|
if (oldValue.text.length > newValue.text.length) {
|
|
return newValue;
|
|
}
|
|
|
|
// Allow only numbers and decimal point
|
|
String filteredText = newValue.text.replaceAll(RegExp(r'[^\d.]'), '');
|
|
|
|
// Only allow one decimal point
|
|
if (filteredText.split('.').length > 2) {
|
|
return oldValue;
|
|
}
|
|
|
|
// Format for three decimal places and auto-insert decimal point
|
|
if (filteredText.contains('.')) {
|
|
List<String> parts = filteredText.split('.');
|
|
String whole = parts[0];
|
|
String fraction = parts[1];
|
|
|
|
// Limit to three decimal places
|
|
if (fraction.length > 3) {
|
|
fraction = fraction.substring(0, 3);
|
|
}
|
|
|
|
// Reconstruct the text
|
|
filteredText = "$whole.$fraction";
|
|
} else {
|
|
// Auto-insert decimal point after the third digit
|
|
if (filteredText.length > 3) {
|
|
String whole = filteredText.substring(0, 3);
|
|
String fraction = filteredText.substring(3);
|
|
|
|
// Limit fraction to three digits
|
|
if (fraction.length > 3) {
|
|
fraction = fraction.substring(0, 3);
|
|
}
|
|
|
|
filteredText = "$whole.$fraction";
|
|
}
|
|
}
|
|
|
|
return TextEditingValue(
|
|
text: filteredText,
|
|
selection: TextSelection.collapsed(offset: filteredText.length),
|
|
);
|
|
}
|
|
}
|