File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments