Intl Phone Number Input

repository·develop·Indexed 41 days ago

https://github.com/natintosh/intl_phone_number_input

A customizable Flutter package for entering international phone numbers, powered by Google's libphonenumber logic. It features as-you-type formatting, RTL support, and multiple country selector modes including DROPDOWN, BOTTOMSHEET, and DIALOG. The package provides the InternationalPhoneNumberInput widget and PhoneNumber class for parsing and validating phone numbers across all Flutter platforms.

Tokens
12K
Snippets
35
Records
45
Agent score
51%

What's inside Intl Phone Number Input

  1. Overview of Intl Phone Number Input

    develop

    Intl Phone Number Input is a customizable Flutter package for inputting phone numbers in international formats. It leverages Google's libphonenumber logic to provide accurate formatting and validation.

    Key Features:

    • Supports all Flutter platforms.
    • Supports RTL (Right-to-Left) languages.
    • Multiple selector modes: DROPDOWN, BOTTOMSHEET, and DIALOG.
    • As-you-type formatting to the selected international format.
    • Ability to filter for a custom list of countries.
    • Tools to retrieve region info and parse phone numbers.
  2. Customize iOS launch screen assets

    develop

    To change the launch screen image for the iOS version of your Flutter application, you can either replace the image files directly in the example/ios/Runner/Assets.xcassets/LaunchImage.imageset/ directory or use Xcode for a more visual approach.

    Using Xcode:

    1. Open your Flutter project's iOS workspace by running open ios/Runner.xcworkspace in your terminal.
    2. In the Xcode Project Navigator, navigate to Runner/Assets.xcassets.
    3. Drag and drop your desired images into the asset catalog to replace the existing ones.
    open ios/Runner.xcworkspace
  3. Common implementation patterns

    develop

    When implementing the InternationalPhoneNumberInput widget, follow these patterns for common tasks:

    Form Integration

    Integrate with a Flutter Form widget and use autoValidateMode (e.g., AutovalidateMode.onUserInteraction) to provide real-time feedback. Always handle the onInputChanged callback to receive the updated PhoneNumber object.

    Form(
      key: _formKey,
      child: InternationalPhoneNumberInput(
        onInputChanged: (PhoneNumber number) {
          // Handle phone number changes
        },
        validator: (String? value) {
          // Custom validation logic
          return null;
        },
        autoValidateMode: AutovalidateMode.onUserInteraction,
      ),
    ),

    Programmatic Control with Controllers

    Use a TextEditingController via the textFieldController property to control the text input programmatically.

    final TextEditingController _controller = TextEditingController();
    
    InternationalPhoneNumberInput(
      textFieldController: _controller,
      onInputChanged: (PhoneNumber number) {
        // number contains the complete phone number data
      },
    )

    Customizing the Selector and Input Decoration

    Use selectorConfig to change the selector type (e.g., PhoneInputSelectorType.BOTTOM_SHEET) and appearance, and inputDecoration for standard Material Design styling.

    InternationalPhoneNumberInput(
      selectorConfig: SelectorConfig(
        selectorType: PhoneInputSelectorType.BOTTOM_SHEET,
        backgroundColor: Colors.blue,
        showFlags: true,
      ),
      inputDecoration: InputDecoration(
        labelText: 'Phone Number',
        border: OutlineInputBorder(),
      ),
    )
  4. Migration guide: 0.7.x to current

    develop

    When migrating from version 0.7.x to the current version:

    • Update pubspec.yaml to the latest version.
    • Breaking Change: getNameForNumber was removed in 0.7.3; replace calls to it.
    • Breaking Change: SelectorConfig.backgroundColor was deprecated in 0.7.0; use theme colors instead.
  5. Run the example applications

    develop

    To run the provided examples, navigate to the example directory and use one of the following methods:

    Option 1: Run a specific example

    cd example
    flutter run lib/basic_example.dart
    # or
    flutter run lib/validation_example.dart
    # or
    flutter run lib/styling_example.dart
    # or
    flutter run lib/advanced_example.dart

    Option 2: Run the main example app This launches a navigation interface to all examples.

    cd example
    flutter run
  6. Configure the country selector display mode

    develop

    You can control how the country selection interface appears using the selectorConfig parameter and the PhoneInputSelectorType enum.

    Available types:

    • PhoneInputSelectorType.DROPDOWN: A standard dropdown menu.
    • PhoneInputSelectorType.BOTTOM_SHEET: A modal that slides up from the bottom.
    • PhoneInputSelectorType.DIALOG: A centered popup dialog.
    selectorConfig: SelectorConfig(
      selectorType: PhoneInputSelectorType.BOTTOM_SHEET,
    ),
  7. Understand the structure of country data

    develop

    The library uses a standardized data model for country information. Each country entry in the list contains geographic codes, dialing information, and localized names. This data is used to populate country selectors and validate phone numbers.

    Each country object includes:

    • alpha_2_code: The 2-letter ISO country code (e.g., VE, VN, ZM).
    • alpha_3_code: The 3-letter ISO country code (e.g., VEN, VNM, ZMB).
    • num_code: The numeric ISO country code.
    • en_short_name: The name of the country in English.
    • nationality: The corresponding nationality string.
    • dial_code: The international dialing prefix (e.g., +58, +84).
    • nameTranslations: A map of language codes to the country's name in that language (e.g., ja for Japanese, zh for Chinese).
    {
      "num_code": "862",
      "alpha_2_code": "VE",
      "alpha_3_code": "VEN",
      "en_short_name": "Venezuela (Bolivarian Republic of)",
      "nationality": "Venezuelan",
      "dial_code": "+58",
      "nameTranslations": {
        "sk": "Venezuela",
        "en": "Venezuela",
        "ja": "ベネズエラ"
      }
    }
  8. Understand the structure of the country list data

    develop

    The countryList provides a collection of maps representing countries available for the phone input. Each country entry contains geographic codes, names, and translations. This data is used to populate country selectors and provide localized names.

    Each country map contains the following keys:

    • num_code: The numeric country code (as a string).
    • alpha_2_code: The ISO 3166-1 alpha-2 country code (e.g., AF, AX, AL).
    • alpha_3_code: The ISO 3166-1 alpha-3 country code (e.g., AFG, ALA, ALB).
    • en_short_name: The English short name of the country.
    • nationality: The demonym or nationality associated with the country.
    • dial_code: The international calling code (e.g., +93, +358).
    • nameTranslations: A map of language codes to the country's name in that language (e.g., ja for Japanese, zh for Chinese).
    {
      "num_code": "4",
      "alpha_2_code": "AF",
      "alpha_3_code": "AFG",
      "en_short_name": "Afghanistan",
      "nationality": "Afghan",
      "dial_code": "+93",
      "nameTranslations": {
        "ja": "アフガニスタン",
        "en": "Afghanistan"
      }
    }
  9. Use InternationalPhoneNumberInput for phone number input

    develop

    The InternationalPhoneNumberInput widget provides a customizable text field for international phone numbers with an integrated country selector. It supports real-time formatting, validation using Google's libphonenumber, and multiple selector display modes (dropdown, bottom sheet, or dialog).

    Key features include:

    • Formatting as you type.
    • Country selection with flags.
    • Real-time validation via onInputValidated.
    • Form integration with validator and onSaved callbacks.
    • Country filtering via ISO codes.
    InternationalPhoneNumberInput(
      onInputChanged: (PhoneNumber number) {
        print(number.phoneNumber);
      },
      onInputValidated: (bool value) {
        print('Is valid: $value');
      },
      selectorConfig: SelectorConfig(
        selectorType: PhoneInputSelectorType.BOTTOM_SHEET,
      ),
      ignoreBlank: false,
      autoValidateMode: AutovalidateMode.disabled,
      selectorTextStyle: TextStyle(color: Colors.black),
      initialValue: PhoneNumber(isoCode: 'NG'),
      textFieldController: myController,
      formatInput: false,
      keyboardType: TextInputType.numberWithOptions(signed: true, decimal: true),
      inputBorder: OutlineInputBorder(),
      onSaved: (PhoneNumber number) {
        print('On Saved: $number');
      },
    )
  10. Integrate with Flutter Forms and Validation

    develop

    The widget is designed to work seamlessly with Flutter's Form widget.

    • Validation: Use the validator callback to return an error message string if the input is invalid. The widget also provides onInputValidated to notify you when the number becomes valid or invalid based on international standards.
    • Saving: Use the onSaved callback to receive the parsed PhoneNumber object when FormState.save() is called.
    // Validation example
    InternationalPhoneNumberInput(
      validator: (String? value) {
        if (value == null || value.isEmpty) {
          return 'Please enter a phone number';
        }
        return null;
      },
      // ...
    )
    
    // Saving example
    InternationalPhoneNumberInput(
      onSaved: (PhoneNumber number) {
        print('Saved: ${number.phoneNumber}');
      },
      // ...
    )
  11. Troubleshoot example execution issues

    develop

    If you encounter issues running the examples, follow these troubleshooting steps:

    1. Install Dependencies: Ensure all packages are installed.
      flutter pub get
    2. Check Flutter Version: Verify you are using Flutter 3.0 or higher.
      flutter --version
    3. Verify Environment: Check your platform configuration.
      flutter doctor