How to add country dial code to TextEditingController in flutter

Issue

I’m using flutter package country_code_picker into my TextFormField and i achieve to put users country dial code into my phone TextEditingController text after they select there country. So if for example in Senegal user put 7712345678, i will get +2217712345678 in my TextEditing controller text. Thanks in advance for help.

here is my code

TextEditingController phoneController = new TextEditingController(text: "");


 Widget _phoneContainer() {
  return new Container(
    child: new TextFormField(
        controller: phoneController,
        decoration: InputDecoration(
            contentPadding: EdgeInsets.symmetric(vertical: 2),
            prefixIcon: CountryCodePicker(
              // Initial selection and favorite can be one of code ('IT') OR dial_code('+39')
              initialSelection: '+221',
              favorite: ['+221', 'SN'],
              textStyle: TextStyle(color: Colors.orange[900]),
              showFlag: true,

               //showFlagDialog: true,
              //comparator: (a, b) => b.name.compareTo(a.name),
              //Get the country information relevant to the initial selection
              //onInit: (code) => print("${code.name} ${code.dialCode}"),
            ),


            labelText: Texts.PHONE_NUMBER_LOGIN,
            focusColor: Colors.orange[900],
            labelStyle: TextStyle(fontSize: 15.0, color: Colors.orange[900]),
            /* hintStyle: TextStyle(
              color: Colors.orange[900]
              ) */
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.all(Radius.circular(20.0)),
              borderSide: const BorderSide(color: Colors.white)
            ),
            focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(20.0)),
                borderSide: const BorderSide(color: Colors.white)
              ),
            hasFloatingPlaceholder: false

            ),
        keyboardType: TextInputType.phone,
        style:TextStyle(
              color: Colors.orange[900],
              decorationColor: Colors.white,
          ),

        ),
    margin: EdgeInsets.only(bottom: 20.0, left: 40.0, right: 40.0),
    color: Colors.white,
    height: 40.0,
    );
  }

Solution

Run this code. On Check Button, it will print your whole phone number (dial code + entered phone number in text field) on console

import 'package:flutter/material.dart';
import 'package:country_code_picker/country_code_picker.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  TextEditingController phoneController = new TextEditingController();
  String phoneNumber = "";

  void _onCountryChange(CountryCode countryCode) {  
    this.phoneNumber =  countryCode.toString();
    print("New Country selected: " + countryCode.toString());
  }

  void check(){
    print("Full Text: "+ this.phoneNumber + phoneController.text);
  }

  @override
  Widget build(BuildContext context) {

    final phone = new TextFormField(
      controller: phoneController,
      keyboardType: TextInputType.phone,
      autofocus: false,
      style: new TextStyle(fontSize:14.0,
        color: Colors.black,
        fontWeight: FontWeight.w400,),
    );

    final checkBtn = RaisedButton(key: null, onPressed: check,
        color:  Colors.blue,
        child:  new Text("Check")
    );

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Country Code Demo'),
        ),
        body: Center(
        child: new ListView(
          shrinkWrap: true,
          padding: EdgeInsets.only(left: 24.0, right: 24.0),
          children: <Widget>[
              CountryCodePicker(
                onChanged: _onCountryChange,
                // Initial selection and favorite can be one of code ('IT') OR dial_code('+39')
                initialSelection: 'IT',
                favorite: ['+39','FR'],
                // optional. Shows only country name and flag
                showCountryOnly: false,
                // optional. Shows only country name and flag when popup is closed.
                showOnlyCountryWhenClosed: false,
                // optional. aligns the flag and the Text left
                alignLeft: false,
              ),
              SizedBox(height: 16.0),
              phone,
              SizedBox(height: 16.0),
              checkBtn
            ]
          ),
        ),
      )
    );
  }
}

Answered By – Muhammad Noman

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *