How to format mobile number based on country code in flutter
Asked Answered
Y

4

7

Can anyone tell me how to format mobile number based on country code. Hope you understand.

enter image description here

here's what I did try so far:

var controller = new MaskedTextController(mask: '(000) 000 0000');

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar( title: Text("Masked Text"), ),
    body: Container(
       child: Row(
          children: <Widget>[
             Expanded(
               child: TextField(
                  controller: controller,
                  keyboardType: TextInputType.number, maxLength: 18,
               ),
             ),
          ],
       )),
   ); 
 }
Yell answered 30/8, 2019 at 11:4 Comment(10)
Where's the code showing what did you try so far ?Furey
var controller = new MaskedTextController(mask: '(000) 000 0000'); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Masked Text"), ), body: Container( child: Row( children: <Widget>[ Expanded( child: TextField( controller: controller, keyboardType: TextInputType.number, maxLength: 18, ), ), ], )), ); }Yell
I've done this one just try to format number. i don't how to do based on country code. Hope you Understand:) Please Help me.Yell
@MazinIbrahim Can you please help me to solve this?Yell
be patient pal ! let me think about a solution.Furey
Okay @MazinIbrahim thank you so much :) Your Help will very appreciated.Yell
you mean the parentheses and spaces right ?Furey
yes, this will also work form me. SO what i want exactly there is two textbox first text box is for country code and second for phone number based on the formatYell
You can get this result using pub.dev/packages/country_code_picker beside your TextField , and let the controller style the text according to the country selection, will you have to implement it by yourself.Furey
I think buddy may it's not work. Can you just create simple snippet of what you say about this. so i can get idea and i am able to implement :) your help is very useful for me:)Yell
D
10

The last class (_UsNumberTextInputFormatter) of the code of Text Form fields for the flutter gallery app can help you out greatly.

The key is to define a inputFormatters for TextFormField.

 

    class _NumberFormatterDemo extends State {
      final List _allActivities = ['+1', '+91'];
      String _activity = '+1';
      _NumberTextInputFormatter _phoneNumberFormatter =
          _NumberTextInputFormatter(1);

      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: const Text('Number Formatter Demo'),
            ),
            body: DropdownButtonHideUnderline(
              child: SafeArea(
                top: false,
                bottom: false,
                child: ListView(
                    padding: const EdgeInsets.all(16.0),
                    children: [
                      const SizedBox(height: 8.0),
                      InputDecorator(
                        decoration: const InputDecoration(
                          labelText: 'Country Code',
                          hintText: 'Select a country code',
                          contentPadding: EdgeInsets.zero,
                        ),
                        isEmpty: _activity == null,
                        child: DropdownButton(
                          value: _activity,
                          onChanged: (String newValue) {
                            setState(() {
                              _activity = newValue;
                              switch(newValue){
                                case '+1':
                                  _phoneNumberFormatter = _NumberTextInputFormatter(1);
                                  break;
                                case '+91':
                                  _phoneNumberFormatter = _NumberTextInputFormatter(91);
                                  break;
                              }
                            });
                          },
                          items: _allActivities
                              .map>((String value) {
                            return DropdownMenuItem(
                              value: value,
                              child: Text(value),
                            );
                          }).toList(),
                        ),
                      ),
                      const SizedBox(height: 24.0),
                      TextFormField(
                        decoration: const InputDecoration(
                          border: UnderlineInputBorder(),
                          filled: true,
                          icon: Icon(Icons.phone),
                          hintText: 'Where can we reach you?',
                          labelText: 'Phone Number *',
                        ),
                        keyboardType: TextInputType.phone,
                        onSaved: (String value) {},
                        inputFormatters: [
                          WhitelistingTextInputFormatter.digitsOnly,
                          // Fit the validating format.
                          _phoneNumberFormatter,
                        ],
                      ),
                    ]),
              ),
            ));
      }
    }

    class _NumberTextInputFormatter extends TextInputFormatter {
      int _whichNumber;
      _NumberTextInputFormatter(this._whichNumber);

      @override
      TextEditingValue formatEditUpdate(
        TextEditingValue oldValue,
        TextEditingValue newValue,
      ) {
        final int newTextLength = newValue.text.length;
        int selectionIndex = newValue.selection.end;
        int usedSubstringIndex = 0;
        final StringBuffer newText = StringBuffer();
        switch (_whichNumber) {
          case 1:
            {
              if (newTextLength >= 1 ) {
                newText.write('(');
                if (newValue.selection.end >= 1) selectionIndex++;
              }
              if (newTextLength >= 4 ) {
                newText.write(
                    newValue.text.substring(0, usedSubstringIndex = 3) + ') ');
                if (newValue.selection.end >= 3) selectionIndex += 2;
              }
              if (newTextLength >= 7 ) {
                newText.write(
                    newValue.text.substring(3, usedSubstringIndex = 6) + '-');
                if (newValue.selection.end >= 6) selectionIndex++;
              }
              if (newTextLength >= 11 ) {
                newText.write(
                    newValue.text.substring(6, usedSubstringIndex = 10) + ' ');
                if (newValue.selection.end >= 10) selectionIndex++;
              }
              break;
            }
          case 91:
            {
              if (newTextLength >= 5) {
                newText.write(
                    newValue.text.substring(0, usedSubstringIndex = 5) + ' ');
                if (newValue.selection.end >= 6) selectionIndex++;
              }
              break;
            }
        }
        // Dump the rest.
        if (newTextLength >= usedSubstringIndex)
          newText.write(newValue.text.substring(usedSubstringIndex));
        return TextEditingValue(
          text: newText.toString(),
          selection: TextSelection.collapsed(offset: selectionIndex),
        );
      }
    }

 

Here is my working example -

Example GIF

Disoblige answered 31/8, 2019 at 13:16 Comment(1)
Thank you so much for your help. it has some little bit error and i fixed them up. :)Yell
Y
1

You can use following phone number formatter:

This formatter converts 00000000 to (000) 000 0000

class PhoneNumberFormatter extends TextInputFormatter {
  PhoneNumberFormatter();

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    
    if (!oldValue.text.contains("(") &&
        oldValue.text.length >= 10 &&
        newValue.text.length != oldValue.text.length) {
      return TextEditingValue(
        text: "",
        selection: TextSelection.collapsed(offset: 0),
      );
    }

    if(oldValue.text.length>newValue.text.length){
      return TextEditingValue(
        text: newValue.text.toString(),
        selection: TextSelection.collapsed(offset: newValue.text.length),
      );
    }

    var newText = newValue.text;
    if (newText.length == 1) newText ="(" + newText;
    if (newText.length == 4) newText = newText + ") ";
    if (newText.length == 9) newText = newText + " ";

    return TextEditingValue(
      text: newText.toString(),
      selection: TextSelection.collapsed(offset: newText.length),
    );
  }
}

For more information: https://www.codesenior.com/en/tutorial/Flutter-Phone-Number-Formatter

Yiyid answered 9/8, 2020 at 10:5 Comment(0)
S
0

A good and easy solution is https://pub.dev/packages/intl_phone_number_input

  final TextEditingController controller = TextEditingController();
  String initialCountry = 'NG';
  PhoneNumber number = PhoneNumber(isoCode: 'NG');

  InternationalPhoneNumberInput(
              onInputChanged: (PhoneNumber number) {
                print(number.phoneNumber);
              },
              onInputValidated: (bool value) {
                print(value);
              },
              selectorConfig: SelectorConfig(
                selectorType: PhoneInputSelectorType.BOTTOM_SHEET,
                backgroundColor: Colors.black,
              ),
              ignoreBlank: false,
              autoValidateMode: AutovalidateMode.disabled,
              selectorTextStyle: TextStyle(color: Colors.black),
              initialValue: number,
              textFieldController: controller,
              inputBorder: OutlineInputBorder(),
            ),
Savina answered 14/12, 2020 at 9:54 Comment(0)
M
0

In case if somebody need to display a us/canada phone formatted inside a text widget. try this;

String formattedPhoneNumber = "(" + phoneNumber.substring(0,3) + ") " + 
phoneNumber.substring(3,6) + "-" +phoneNumber.substring(6,phoneNumber.length);
Metaprotein answered 23/9, 2022 at 9:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.