How to remove 0 numbers without loosing your cursor position.
Asked
Active
Viewed 949 times
4

Kherel
- 14,882
- 5
- 50
- 80
-
This might be the [answer](https://stackoverflow.com/a/64368082/12913325) you are looking for. – Jay_Panchal Jan 27 '23 at 20:01
3 Answers
6
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
FilteringTextInputFormatter.deny(RegExp('^0+'))
]

Linar
- 903
- 6
- 10
0
TextField(
controller: controller,
onChanged: (value) {
var selection = controller.selection;
final RegExp regexp = new RegExp(r'^0+(?=.)');
var match = regexp.firstMatch(value);
var matchLengh = match?.group(0)?.length ?? 0;
if (matchLengh != 0) {
controller.text = value.replaceAll(regexp, '');
controller.selection = TextSelection.fromPosition(
TextPosition(
offset: math.min(matchLengh, selection.extent.offset),
),
);
}
},
// keyboardType and inputFormatters not realy needed in this case but maybe usefull
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
],
...
)

Kherel
- 14,882
- 5
- 50
- 80
-1
you can also try to convert string into int or double to get rid out of leading zeros, like below example.
TextField(
controller: controller,
onChanged: (value) {
controller.text = int.parse(value).toString();
},
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
],
....
)

Shubhanshu Kashiva
- 136
- 1
- 1
- 7