Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format string to phone number with (123) 456-6789 pattern using dart

Tags:

flutter

dart

Here is my code

void main() {

  String phoneNumber = '123456789';

  String formattedPhoneNumber = phoneNumber.replaceFirst("(\d{3})(\d{3})(\d+)", "(\$1) \$2-\$3");

  print('Formatted number ${formattedPhoneNumber}');

}

Output:

Formatted number 123456789

I want output as Formatted number (123) 456-6789

like image 888
Darshan Prajapati Avatar asked Feb 06 '20 10:02

Darshan Prajapati


3 Answers

Create a custom Masked class

import 'package:flutter/material.dart';

class MaskedTextController extends TextEditingController {
  MaskedTextController({String text, this.mask, Map<String, RegExp> translator})
      : super(text: text) {
    this.translator = translator ?? MaskedTextController.getDefaultTranslator();

    this.addListener(() {
      var previous = this._lastUpdatedText;
      if (this.beforeChange(previous, this.text)) {
        this.updateText(this.text);
        this.afterChange(previous, this.text);
      } else {
        this.updateText(this._lastUpdatedText);
      }
    });

    this.updateText(this.text);
  }

  String mask;

  Map<String, RegExp> translator;

  Function afterChange = (String previous, String next) {};
  Function beforeChange = (String previous, String next) {
    return true;
  };

  String _lastUpdatedText = '';

  void updateText(String text) {
    if(text != null){
      this.text = this._applyMask(this.mask, text);
    }
    else {
      this.text = '';
    }

    this._lastUpdatedText = this.text;
  }

  void updateMask(String mask, {bool moveCursorToEnd = true}) {
    this.mask = mask;
    this.updateText(this.text);

    if (moveCursorToEnd) {
      this.moveCursorToEnd();
    }
  }

  void moveCursorToEnd() {
    var text = this._lastUpdatedText;
    this.selection = new TextSelection.fromPosition(
        new TextPosition(offset: (text ?? '').length));
  }

  @override
  void set text(String newText) {
    if (super.text != newText) {
      super.text = newText;
      this.moveCursorToEnd();
    }
  }

  static Map<String, RegExp> getDefaultTranslator() {
    return {
      'A': new RegExp(r'[A-Za-z]'),
      '0': new RegExp(r'[0-9]'),
      '@': new RegExp(r'[A-Za-z0-9]'),
      '*': new RegExp(r'.*')
    };
  }

  String _applyMask(String mask, String value) {
    String result = '';

    var maskCharIndex = 0;
    var valueCharIndex = 0;

    while (true) {
      // if mask is ended, break.
      if (maskCharIndex == mask.length) {
        break;
      }

      // if value is ended, break.
      if (valueCharIndex == value.length) {
        break;
      }

      var maskChar = mask[maskCharIndex];
      var valueChar = value[valueCharIndex];

      // value equals mask, just set
      if (maskChar == valueChar) {
        result += maskChar;
        valueCharIndex += 1;
        maskCharIndex += 1;
        continue;
      }

      // apply translator if match
      if (this.translator.containsKey(maskChar)) {
        if (this.translator[maskChar].hasMatch(valueChar)) {
          result += valueChar;
          maskCharIndex += 1;
        }

        valueCharIndex += 1;
        continue;
      }

      // not masked value, fixed char on mask
      result += maskChar;
      maskCharIndex += 1;
      continue;
    }

    return result;
  }
}

Now call it in your main dart file

var maskedController = MaskedTextController(mask: '(000) 000-0000');

TextField(
  controller: maskedController,
  style: Styles.textNormalStyle,
  maxLines: 1,
),
like image 134
Nitesh Kumar Verma Avatar answered Oct 16 '22 00:10

Nitesh Kumar Verma


Try this

print('1234567890'.replaceAllMapped(RegExp(r'(\d{3})(\d{3})(\d+)'), (Match m) => "(${m[1]}) ${m[2]}-${m[3]}"));
like image 36
Pongpon Tienthong Avatar answered Oct 15 '22 23:10

Pongpon Tienthong


This solution work for your this specific Question and scenario.

you can achieve using following code.

String formattedPhoneNumber = "(" + phoneNumber.substring(0,3) + ") " + 
phoneNumber.substring(3,6) + "-" +phoneNumber.substring(6,phoneNumber.length);
like image 21
Viren V Varasadiya Avatar answered Oct 15 '22 23:10

Viren V Varasadiya