[Flutter/Dart] Format string with TextField
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.
Recent Posts
See AllWhat want to do There is a variable that remain unchanged once the initial value is determined. However, it cannot be determined yet when...
What want to do As the title suggests. Place two widgets in one line on the screen One in the center of the screen and the other on the...
Phenomenon Certain icons perform certain actions when long-pressed To achieve this, I registered the actions in GestureDetector's...
Comments