You should use the controller property from the TextFormField
class.
- You'll need to make your widget a stateful one (we'll need it's dispose method).
- Add the
controller
to your state:
final _textController = TextEditingController();
@override
void dispose() {
super.dispose();
_textController.dispose();
}
- Add a listener to your
controller
to format your input whenever you type:
@override
void initState() {
super.initState();
_textController.addListener(() {
// using Ashok's answer to format the text
final reg_ex = new RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))');
final matchFunc = (Match match) => '${match[1]},';
final text = _textController.text;
_textController.value = _textController.value.copyWith(
// we need to remove all the ',' from the values before reformatting
// if you use other formatting values, remember to remove them here
text: text.replaceAll(',', '').replaceAllMapped(reg_ex, matchFunc),
// this will keep the cursor on the right as you type in values
selection: TextSelection(
baseOffset: text.length,
extentOffset: text.length,
),
);
});
}
- Use the
controller
within your TextFormField
:
TextFormField(
controller: _textController,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Email Address',
hintText: 'you@example.com',
),
)