A flutter package for showing a country code selector.

Overview

Pub

country_code_picker

A flutter package for showing a country code selector.

It supports i18n for 70 languages.

Check the example on web! https://imtoori.dev/CountryCodePicker/#/

Usage

Just put the component in your application setting the onChanged callback.

@override
 Widget build(BuildContext context) => new Scaffold(
     body: Center(
       child: CountryCodePicker(
         onChanged: print,
         // 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,
       ),
     ),
 );

Example:

void _onCountryChange(CountryCode countryCode) {
    //TODO : manipulate the selected country code here
    print("New Country selected: " + countryCode.toString());
  }

i18n

Just add the CountryLocalizations.delegate in the list of your app delegates

 return new MaterialApp(
      supportedLocales: [
         Locale("af"),
        Locale("am"),
        Locale("ar"),
        Locale("az"),
        Locale("be"),
        Locale("bg"),
        Locale("bn"),
        Locale("bs"),
        Locale("ca"),
        Locale("cs"),
        Locale("da"),
        Locale("de"),
        Locale("el"),
        Locale("en"),
        Locale("es"),
        Locale("et"),
        Locale("fa"),
        Locale("fi"),
        Locale("fr"),
        Locale("gl"),
        Locale("ha"),
        Locale("he"),
        Locale("hi"),
        Locale("hr"),
        Locale("hu"),
        Locale("hy"),
        Locale("id"),
        Locale("is"),
        Locale("it"),
        Locale("ja"),
        Locale("ka"),
        Locale("kk"),
        Locale("km"),
        Locale("ko"),
        Locale("ku"),
        Locale("ky"),
        Locale("lt"),
        Locale("lv"),
        Locale("mk"),
        Locale("ml"),
        Locale("mn"),
        Locale("ms"),
        Locale("nb"),
        Locale("nl"),
        Locale("nn"),
        Locale("no"),
        Locale("pl"),
        Locale("ps"),
        Locale("pt"),
        Locale("ro"),
        Locale("ru"),
        Locale("sd"),
        Locale("sk"),
        Locale("sl"),
        Locale("so"),
        Locale("sq"),
        Locale("sr"),
        Locale("sv"),
        Locale("ta"),
        Locale("tg"),
        Locale("th"),
        Locale("tk"),
        Locale("tr"),
        Locale("tt"),
        Locale("uk"),
        Locale("ug"),
        Locale("ur"),
        Locale("uz"),
        Locale("vi"),
        Locale("zh")
      ],
      localizationsDelegates: [
        CountryLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],

Customization

Here is a list of properties available to customize your widget:

Name Type Description
onChanged ValueChanged callback invoked when the selection changes
onInit ValueChanged callback invoked during initialization of the widget
initialSelection String used to set the initial selected value
favorite List used to populate the favorite country list
textStyle TextStyle TextStyle applied to the widget button
padding EdgeInsetsGeometry the padding applied to the button
showCountryOnly bool true if you want to see only the countries in the selection dialog
searchDecoration InputDecoration decoration applied to the TextField search widget
searchStyle TextStyle style applied to the TextField search widget text
emptySearchBuilder WidgetBuilder use this to customize the widget used when the search returns 0 elements
builder Function(CountryCode) use this to build a custom widget instead of the default FlatButton
enabled bool set to false to disable the widget
textOverflow TextOverflow the button text overflow behaviour
dialogSize Size the size of the selection dialog
countryFilter List uses a list of strings to filter a sublist of countries
showOnlyCountryWhenClosed bool if true it'll show only the country
alignLeft bool aligns the flag and the Text to the left
showFlag bool shows the flag everywhere
showFlagMain bool shows the flag only when closed
showFlagDialog bool shows the flag only in dialog
flagWidth double the width of the flags
flagDecoration Decoration used for styling the flags
comparator Comparator use this to sort the countries in the selection dialog
hideSearch bool if true the search feature will be disabled

Contributions

Contributions of any kind are more than welcome! Feel free to fork and improve country_code_picker in any way you want, make a pull request, or open an issue.

Comments
  • Listview scrolling and selecting Textfield afterwards is freezing my app

    Listview scrolling and selecting Textfield afterwards is freezing my app

    I am using flutter 1.17.3 and

      country_code_picker: ^1.4.0
    

    @imtoori I am on a tight deadline for a project, so a quick response would be appreciated.

    When I run this code

        import 'package:country_code_picker/country_code_picker.dart';
        import 'package:flutter/material.dart';
        
        void main() {
          runApp(App());
        }
        
        class App extends StatelessWidget {
          App();
        
          @override
          Widget build(BuildContext context) {
            return MaterialApp(
              debugShowCheckedModeBanner: false,
              home: TestWidget(),
            );
          }
        }
        
        class TestWidget extends StatelessWidget {
          @override
          Widget build(BuildContext context) {
            return _buildCountryPicker(context);
          }
        
            Widget _buildCountryPicker(BuildContext context) {
        
            return Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              child: Center(
                child: CountryCodePicker(
                  initialSelection: 'NL',
                ),
              ),
            );
          }
        }
    

    And I open the dialog to select a country. I scroll in the list and then select the TextField my keyboard opens and when I try to type something my entire app freezes. I can't even hot reload. I forked the repo and tried to fix it, except for that I don't have a singly clue what it could be.

    I am running this on my Huawei P30, but I also experience this on other android devices. I don't know if this is a flutter bug or a country code picker bug.

    I think it is probably in this widget somewhere.

    class SelectionDialog extends StatefulWidget {
          final List<CountryCode> elements;
          final bool showCountryOnly;
          final InputDecoration searchDecoration;
          final TextStyle searchStyle;
          final TextStyle textStyle;
          final WidgetBuilder emptySearchBuilder;
          final bool showFlag;
          final double flagWidth;
          final Size size;
          final bool hideSearch;
        
          /// elements passed as favorite
          final List<CountryCode> favoriteElements;
        
          SelectionDialog(
            this.elements,
            this.favoriteElements, {
            Key key,
            this.showCountryOnly,
            this.emptySearchBuilder,
            InputDecoration searchDecoration = const InputDecoration(),
            this.searchStyle,
            this.textStyle,
            this.showFlag,
            this.flagWidth = 32,
            this.size,
            this.hideSearch = false,
          })  : assert(searchDecoration != null, 'searchDecoration must not be null!'),
                this.searchDecoration =
                    searchDecoration.copyWith(prefixIcon: Icon(Icons.search)),
                super(key: key);
        
          @override
          State<StatefulWidget> createState() => _SelectionDialogState();
        }
        
        class _SelectionDialogState extends State<SelectionDialog> {
          /// this is useful for filtering purpose
          List<CountryCode> filteredElements;
        
          @override
          Widget build(BuildContext context) => SimpleDialog(
                titlePadding: const EdgeInsets.all(0),
                title: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    IconButton(
                      padding: const EdgeInsets.all(0),
                      iconSize: 20,
                      icon: Icon(
                        Icons.close,
                      ),
                      onPressed: () => Navigator.pop(context),
                    ),
                    if (!widget.hideSearch)
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 24),
                        child: TextField(
                          style: widget.searchStyle,
                          decoration: widget.searchDecoration,
                          onChanged: _filterElements,
                        ),
                      ),
                  ],
                ),
                children: [
                  Container(
                    width: widget.size?.width ?? MediaQuery.of(context).size.width,
                    height:
                        widget.size?.height ?? MediaQuery.of(context).size.height * 0.7,
                    child: ListView(
                      children: [
                        widget.favoriteElements.isEmpty
                            ? const DecoratedBox(decoration: BoxDecoration())
                            : Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  ...widget.favoriteElements.map(
                                    (f) => SimpleDialogOption(
                                      child: _buildOption(f),
                                      onPressed: () {
                                        _selectItem(f);
                                      },
                                    ),
                                  ),
                                  const Divider(),
                                ],
                              ),
                        if (filteredElements.isEmpty)
                          _buildEmptySearchWidget(context)
                        else
                          ...filteredElements.map(
                            (e) => SimpleDialogOption(
                              key: Key(e.toLongString()),
                              child: _buildOption(e),
                              onPressed: () {
                                _selectItem(e);
                              },
                            ),
                          ),
                      ],
                    ),
                  ),
                ],
              );
        
          Widget _buildOption(CountryCode e) {
            return Container(
              width: 400,
              child: Flex(
                direction: Axis.horizontal,
                children: <Widget>[
                  if (widget.showFlag)
                    Flexible(
                      child: Padding(
                        padding: const EdgeInsets.only(right: 16.0),
                        child: Image.asset(
                          e.flagUri,
                          package: 'country_code_picker',
                          width: widget.flagWidth,
                        ),
                      ),
                    ),
                  Expanded(
                    flex: 4,
                    child: Text(
                      widget.showCountryOnly
                          ? e.toCountryStringOnly()
                          : e.toLongString(),
                      overflow: TextOverflow.fade,
                      style: widget.textStyle,
                    ),
                  ),
                ],
              ),
            );
          }
        
          Widget _buildEmptySearchWidget(BuildContext context) {
            if (widget.emptySearchBuilder != null) {
              return widget.emptySearchBuilder(context);
            }
        
            return Center(
              child: Text('No country found'),
            );
          }
        
          @override
          void initState() {
            filteredElements = widget.elements;
            super.initState();
          }
        
          void _filterElements(String s) {
            s = s.toUpperCase();
            setState(() {
              filteredElements = widget.elements
                  .where((e) =>
                      e.code.contains(s) ||
                      e.dialCode.contains(s) ||
                      e.name.toUpperCase().contains(s))
                  .toList();
            });
          }
        
          void _selectItem(CountryCode e) {
            Navigator.pop(context, e);
          }
        }
    
    opened by duck-dev-go 14
  • Allow custom settings of FlatButton or builder with no InkWell

    Allow custom settings of FlatButton or builder with no InkWell

    There is no arguments to pass in the settings of FlatButton such as shape, border and elevation.

    In addition, even if you use builder, the widget returned from the builder function is automatically wrapped with InkWell, preventing you from customising the handling of tap events.

    I actually managed to make the ripple effect invisible by making splashColor and highlightColor transparent and wrap InkWell with another button, in an attempt to handle tap events on my own. It achieved my desired look but with no more luck because there is no way of manually showing the picker dialog, as mentioned in #60.

    opened by kaboc 7
  • Allow to filter countries by locale in the dialog

    Allow to filter countries by locale in the dialog

    This commit is for letting the user search / filter a country in the dialog using the selected locale.

    Fixes #62 and Fixes #48

    I added a flag in the constructor so that a user can still search using the original name in the country_codes json file.

    opened by themobilecoder 7
  • missing flag icons on android

    missing flag icons on android

    I too have the problem that some icons are not shown (some others are). This was on Android 5.1, I guess that the device I have (Lenovo Vibe K5) is not supporting some fonts.

    Maybe there is the chance to combine this package with this one? https://pub.dartlang.org/packages/country_icons

    imagen

    opened by Chris1234567899 6
  • while tapping

    while tapping "US" from dialog picker selects Canada as a selected country.

    To Reproduce: 1> open country dialogue 2> Type "us" into search fields 3> Then Select the USA from list..

    after this steps you will get "Canada" as a selected country, for the first time after initialising country picker. can you please guide me ?

    waiting for response 
    opened by DhrumilShah11 5
  • When create custom picker flag image can't be accesses

    When create custom picker flag image can't be accesses

    builder: (CountryCode) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(CountryCode.code), Image.asset(CountryCode.flagUri), Icon(Icons.arrow_drop_down) ]); },

    flutter: Another exception was thrown: Unable to load asset: flags/jo.png

    opened by areejmayadeh 4
  • Edit font styles and colours on country dialog

    Edit font styles and colours on country dialog

    Is there an option to format and style the dialog widget where the country and country code is selected? Currently, mine displays as blank, and I could really use some tips pointing me on how to go about it.

    This is an image of what I have - MicrosoftTeams-image

    opened by twumm 4
  • Design issues and Overflow

    Design issues and Overflow

    Hi,

    Can you please adapt your code?

    1. Can we have the option to remove the bold text when we show Flag+Country Name or whatever?

    2. Flags size are different;

    3. Can we have the option to change the padding? The actual option don't work;

    4. When I have Flag+Country Name and something else on the left size (like icon or whatever), the countries with big name get overflow/error. Can they please go Flexible/Multiple lines?

    All the above should be easy. THANK YOU for this awesome lib.

    opened by FilipeOS 4
  • Arabic language not showing properly

    Arabic language not showing properly

    I'm using the latest version and on flutter stable channel

    the arabic language is not showing on the dialog properly like showing on the picture

    this is on the iOS version

    don't know if it is the same for Android

    like you can see it's displaying the characters separated

    Screenshot 2019-03-12 21 14 08 Screenshot 2019-03-12 21 14 22

    UAE -> should be "دولة اللإمارت العربية المتحدة" not " د و ل ة ا ل ا ل إ م ا ر ا ت ا ل ع ر ب ي ة ا ل م ت ح د ة" YMEN -> should be "اليمن" not "ا ل ي م ن" and same goes for all the arabic countries

    also it is not working on typing too!

    Screenshot 2019-03-12 21 24 53

    one more issues that I found that it make my hole arabic langue messed up after selecting an arabic country

    Screenshot 2019-03-12 21 35 41
    opened by AminFadul 4
  • Countries that presented in modal aren't presented in CountryManager

    Countries that presented in modal aren't presented in CountryManager

    These countries are presented in view. but aren't accessible via CountryManager(); +672 Antarctica +47 Bouvet Island +262 French Southern Territories +0 Heard Island and Macdonald Islands +599 Netherlands Antilles +64 Pitcairn +500 South Georgia and the South Sandwich Islands

    For example +672 Antarctica: onChanged callback returns country code 'AQ' then calling CountryManager().countries.firstWhere((element) => element.countryCode == 'AQ', orElse: () => null) returns null

    the same goes for another countries in the list above.

    waiting for response 
    opened by Veargan 3
  • [Flutter Web] Text not appearing in country picker

    [Flutter Web] Text not appearing in country picker

    On Flutter web, when I open the country picker, the text and search bar are blank:

    image

    Here's my TextFormField definition:

    TextFormField(
        controller: _phoneController,
        keyboardType: TextInputType.phone,
        decoration: InputDecoration(
            hintText: 'Enter your phone number',
            labelText: 'Phone',
            prefixIcon: CountryCodePicker(
            onChanged: (CountryCode code) {
                _countryCode = code.dialCode;
            },
            initialSelection: '+1',
            favorite: ['+1', 'US'],
        ),
    )
    
    opened by lmordell 3
  • Is the repo dead?

    Is the repo dead?

    Last commit was 13 months ago and pr's are going back to mid '21 without any reactions from @imtoori

    Seems like the repo is dead. Does anybody already maintain an active fork?

    opened by xtrcode 1
  • Exclude countries

    Exclude countries

    It's currently not possible to exclude countries. The filter is meant to keep only the specified countries. This instead will remove the specified countries from the full list.

    opened by aakrem 1
  • Country code is same then country flag is change automatically after profile updating

    Country code is same then country flag is change automatically after profile updating

    I have an issue regarding this package is that , If country code is same for more than 2 countries (For ex :- US and Canada), then country flag is change automatically after I update my profile screen. If I select my country code +1 with USA it display well at first time with proper USA flag , but after it if I enter my profile screen again then I get country code +1 with Canada flag even if I don't change it from USA to Canada.

    Please provide me better solution regarding above issue :)

    opened by iamvaidarbhi 0
  • Flickering after localizationOverride (PageView)

    Flickering after localizationOverride (PageView)

    In some cases the delegates produces some ugly side effects.

    In my app we have a PageView and each page comes from another flutter module. To show the String resources from the correct module a localization override is needed in the page. While scrolling the page in the PageView the page is flickering in the moment the next page is arriving the screen.

    Workaround: To fix that problem we removed the CountryLocalizations.delegate from the MaterialApp widget and wrap the CountryCodePicker into a Localizations.override widget with a Builder as child.

    opened by mauriceraguseinit 0
Owner
Salvatore Giordano
Flutter team lead @GetStream ⛵ Born in Sicily 🏝️ Lliving in Amsterdam 🇳🇱
Salvatore Giordano
Item Selector for Flutter

Item Selector for Flutter A generic Flutter item selector that works with ListView, GridView, Row, Column, or basically any parent widget that can hav

J-P Nurmi 5 Sep 28, 2022
Tag Selector Text

Welcome to Flutter Tag Selector! The fluttertagselector is a flutter package which you can use to create bubble tag selector as show in the below scre

Hemant Khorwal 4 Feb 18, 2021
Flutter package to show and pick country code

country list pick Flutter plugin to pick country with output name, code, dialcode and flag of country Usage To use this plugin, add country_list_pick

fiaz 69 Nov 13, 2022
A Dart package that provides a customizable country phone code picker for your Flutter application

A Flutter package that provides an easy and customizable country phone code picker widget! Features This package comes with a lot of customization all

Samit Kapoor 1 Oct 1, 2022
A flutter plugin about qr code or bar code scan , it can scan from file、url、memory and camera qr code or bar code .Welcome to feedback your issue.

r_scan A flutter plugin about qr code or bar code scan , it can scan from file、url、memory and camera qr code or bar code .Welcome to feedback your iss

PengHui Li 112 Nov 11, 2022
It is a Flutter mobile and web application that allows you to search for universities worldwide by name and country.

Search Universities App It is a Flutter mobile and web application that allows you to search for universities worldwide by name and country. Data sour

Enes 1 Feb 4, 2022
Animated dialog box - A pure dart package for showing animated alert box.

animated_dialog_box A pure dart package for showing animated alert box. Getting Started https://github.com/Shubham-Narkhede/animated_dialog_box/blob/m

Shubham-Narkhede 10 Jul 24, 2022
Status Stepper: Use this package for showing status changing

status_stepper Use this package for showing status changing. For now available o

Progressive Mobile 0 Jan 11, 2022
A simple Flutter app showing cat images from CatApi

CAT APP A simple Flutter app showing cat images from CatApi USE Bloc REST API St

null 0 Jan 10, 2022
A simple yet powerful Flutter plugin for showing Toast at Android, iOS and Web.

Flutter Toast A simple yet powerful Flutter plugin for showing Toast at Android and iOS. Features: Native Toast Pure Flutter Toaster Installation Add

Eyro Labs 5 Dec 13, 2021
Crypto-currency - A Flutter application showing crypto currency rates

Features Crypto Currency rates This application allows to view crypto currency rates from Coin Market Cap. Getting started Get an API key at Coin Mark

Karol Lisiewicz 16 Oct 26, 2022
Flutterbiometric - A sample app showing how to implement biometric authentication in flutter

Flutter Tutorial - Fingerprint & Touch ID - Local Auth By using Flutter Local Au

null 0 Jan 1, 2022
Flutter Project showing random image with GETX

RdmImageWithGETX Présentation RdmImageWithGETX est un projet développé en Flutter durant le module "Développement Mobile" à l'école Ynov Lyon Campus.

Clement Guyon 1 Mar 8, 2022
Just a simple interface showing a diamond, an imitation to that old application called I am rich .

i_am_rich A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if thi

Nixi 0 Dec 29, 2021
A small transitioning dynamic app showing Dice changing Behavior

Dice_App A new Flutter project.This is a small transitioning dynamic app showing Dice changing Behavior. Getting Started This project is a starting po

Avinandan Bose 1 Mar 20, 2022
This Crypto App is Simply Showing data and chart by using coin gecko api.

crypto_app This is Simple Crypto Currency analytics showing app using coingecko api. You Can Use this if you want to show simply crypto currency analy

null 2 Oct 7, 2022
An application that helps you to quit smoking by showing your everyday performance and boosting your confidence.

This Project is developed in HACKTOBERFEST 2022 By I Can And I Will An application that helps you to quit smoking by showing your everyday performance

Kalash Saini 10 Oct 27, 2022
Write iOS&Android Code using Dart. This package liberates you from redundant glue code and low performance of Flutter Channel.

Dart_Native Dart_Native operates as both a code generator tool and a bridge to communicate between Dart and native APIs. Replaces the low-performing F

DartNative 893 Jan 4, 2023
Code-quizzy - Code Quizzy Application Built With Flutter

Flutter Code Quizzy Application Configuration for this application Fortunately,

Nijat Namazzade 21 Jan 1, 2023