[Flutter/Dart] Format string with TextField
- M.R

- Feb 11, 2024
- 1 min read
What want to do
I want to create an input form using TextField.
For example, if the input content is a monetary amount, I would like to display it in 3-digit delimiters with a ¥ prefix.
Rather than having the user enter these numbers, I would like the user to just enter the numbers and the app will automatically format them.
Method
This can be achieved by inheriting TextInputFormatter and adding the desired formatting process.
See for example this article .
Below I will explain what I personally encountered.
Input to formatEditUpdate
The input to formatEditUpdate, that is, the argument oldValue, is the formatted string.
Nnot the number entered by the user.
Value of TextEditingValue.selection
Recalculate the number of characters after formatting.
Originally I set TextEditingValue.selection as newValue.selection, but in this case
if the number of characters after formatting becomes shorter, it will reference outside the range, and the following error occurred in formatEditUpdate
Range start <int> is out of text of length <int>
Response to input value ""
Even if TextField.keybordType is set to TextInputType.number, there is a possibility that “” will appear.
For example, when all input is deleted.
TextField.maxLength value
If the formatting process changes the number of characters (for example, when adding ¥ or ,), set the length after formatting.






Comments