Skip to content

Commit c337149

Browse files
committed
Add custom value formatter to deal better with minimal default values
1 parent 8081d00 commit c337149

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import 'package:flutter/services.dart';
2+
3+
class MinValueFormatter extends TextInputFormatter {
4+
final int min;
5+
6+
MinValueFormatter(this.min);
7+
8+
@override
9+
TextEditingValue formatEditUpdate(
10+
TextEditingValue oldValue,
11+
TextEditingValue newValue,
12+
) {
13+
var text = newValue.text;
14+
var selectionIndex = newValue.selection.end; // keep track of cursor
15+
16+
if (text.isEmpty) {
17+
text = min.toString();
18+
selectionIndex = text.length;
19+
} else {
20+
// Strip leading zeros (but not a single "0")
21+
if (text.length > 1 && text.startsWith('0')) {
22+
final withoutLeadingZeros = int.parse(text).toString();
23+
// Adjust cursor position by how many zeros we cut
24+
selectionIndex -= (text.length - withoutLeadingZeros.length);
25+
text = withoutLeadingZeros;
26+
}
27+
28+
// Enforce min
29+
final parsed = int.tryParse(text);
30+
if (parsed == null || parsed < min) {
31+
text = min.toString();
32+
selectionIndex = text.length;
33+
}
34+
}
35+
36+
// Clamp selection to valid range
37+
selectionIndex = selectionIndex.clamp(0, text.length);
38+
39+
return TextEditingValue(
40+
text: text,
41+
selection: TextSelection.collapsed(offset: selectionIndex),
42+
composing: TextRange.empty,
43+
);
44+
}
45+
}

0 commit comments

Comments
 (0)