Custom money TextField in Flutter

Viewed 183

I just started learning Flutter and i am trying to figure out how the user can enter an amount in a TextField ,for example 1234567 , should look like this when user is typing :

1.00
12.00
123.00
1 234.00
12 345.00
123 456.00
1 234 567.00

I tried using this library : mask_text_input_formatter, but i can't figure out how to do it. Here is my code

 var maskFormatter = new MaskTextInputFormatter(
      mask: '### ### ###.00', filter: {"#": RegExp(r'[0-9]')});

TextFormField(
keyboardType: TextInputType.number,
inputFormatters: [maskFormatter],
onChanged: (value) {},
decoration: InputDecoration(
prefixIcon: Icon(Icons.monetization_on),
 hintText: 'Amount',
 border: OutlineInputBorder(),
 ),
   validator: (value) {
   if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),

Any idea on how to achieve that result.

1 Answers

Declare and initialize a text controller and assign it to the text field. Update its value on change in input!

TextEditingController _moneyController = TextEditingController();
@override
void initState() { 
  super.initState();
  _moneyController.text = '.00';
}

TextFormField(
keyboardType: TextInputType.number,
inputFormatters: [maskFormatter],
onChanged: (value) {},
decoration: InputDecoration(
prefixIcon: Icon(Icons.monetization_on),
 hintText: 'Amount',
 border: OutlineInputBorder(),
 ),
   validator: (value) {
   if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
//added code here
controller: _moneyController,
),
Related