thomas.s
thomas.s

Reputation: 348

how to format or separate textformfield parts in flutter

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

Answers (2)

EdYuTo
EdYuTo

Reputation: 6884

You should use the controller property from the TextFormField class.

  1. You'll need to make your widget a stateful one (we'll need it's dispose method).
  2. Add the controller to your state:
  final _textController = TextEditingController();

  @override
  void dispose() {
    super.dispose();
    _textController.dispose();
  }
  1. 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,
        ),
      );
    });
  }
  1. Use the controller within your TextFormField:
  TextFormField(
    controller: _textController,
    keyboardType: TextInputType.emailAddress,
    decoration: InputDecoration(
      labelText: 'Email Address',
      hintText: '[email protected]',
    ),
  )

Upvotes: 2

Ashok
Ashok

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

Related Questions