You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
workingHoursFlutter/lib/utils/input_formatters.dart

58 lines
1.5 KiB
Dart

import 'package:flutter/services.dart';
/// Formatiert Eingaben als HH:mm (max. 5 Zeichen),
/// lässt nur Ziffern und optional ":" an Pos 2 zu.
/// Fügt bei Bedarf ":" automatisch ein.
class HHmmInputFormatter extends TextInputFormatter {
const HHmmInputFormatter();
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
var text = newValue.text;
// nur Ziffern und ":" erlauben
final filtered = StringBuffer();
for (int i = 0; i < text.length; i++) {
final c = text[i];
if ((c.codeUnitAt(0) >= 48 && c.codeUnitAt(0) <= 57) || c == ':') {
filtered.write(c);
}
}
text = filtered.toString();
// Länge begrenzen
if (text.length > 5) text = text.substring(0, 5);
// ":" automatisch einfügen
if (text.length >= 3) {
if (text[2] != ':') {
text = text.replaceRange(2, 2, ':');
}
}
// nur ein ":" erlauben, und nur an Stelle 2
if (text.contains(':')) {
final idx = text.indexOf(':');
if (idx != 2) {
text = text.replaceAll(':', '');
if (text.length >= 2) {
text = '${text.substring(0, 2)}:${text.substring(2)}';
}
} else {
// weitere ":" entfernen
final rest = text.substring(3).replaceAll(':', '');
text = text.substring(0, 3) + rest;
}
}
// Cursor ans Ende
return TextEditingValue(
text: text,
selection: TextSelection.collapsed(offset: text.length),
);
}
}