Reputation: 348
i have a text form field i want to separating the text that comes to text form field
let's say user writes 1111111
and output will be 1,111,111
Form(
child: Column(
children: [
TextFormField(
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Email Address',
hintText: '[email protected]',
),
)
],
),
),
Upvotes: 1
Views: 2172
Reputation: 6884
You should use the controller property from the TextFormField
class.
controller
to your state: final _textController = TextEditingController();
@override
void dispose() {
super.dispose();
_textController.dispose();
}
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,
),
);
});
}
controller
within your TextFormField
: TextFormField(
controller: _textController,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Email Address',
hintText: '[email protected]',
),
)
Upvotes: 2
Reputation: 3611
RegExp reg_ex = new RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))');
Function mathFunc = (Match match) => '${match[1]},';
List<String> sample = [
'1111111',
];
sample.forEach((String str) {
String result = str.replaceAllMapped(reg_ex, mathFunc);
print('$str -> $result');
});
Upvotes: 2