intl_phone_input: a Flutter phone field that formats, detects and validates
A phone number field is in almost every sign-up form, and it is harder than it looks. Users type their number with a leading zero, or paste it from their contacts as +213 555 12 34 56, or as 00213555123456. Some type Arabic-Indic digits.
The same dial code can belong to several countries: +1 covers the US, Canada, Puerto Rico and others. And "valid" depends on the country and on the type of number, because a landline is not what you want for an SMS code.
intl_phone_input is a phone number field for Flutter with a country picker. It formats the number as the user types, detects pasted international numbers, and validates against libphonenumber metadata. The README describes it as a maintained replacement for intl_phone_field.
What it does
A real form field. IntlPhoneInput wraps a TextFormField, so it works in a Form with validate(), save(), a controller, a focusNode and autofill (AutofillHints.telephoneNumber).
Formats as you type. 555 12 34 56, (201) 555-0123, 7400 123456, depending on the country. After every insert, delete or paste, the cursor stays next to the same digit. A backspace over a separator deletes the digit before it.
Paste detection. Pasting +213 555 12 34 56 or 00213555123456 switches the country to Algeria and keeps 555 12 34 56. Typing +213 key by key does the same.
Shared dial codes. +1 (US, CA, PR, JM and others), +7 (RU, KZ), +44 (GB, GG, JE, IM) and the rest are told apart by their leading digits.
Real lengths and patterns. The field refuses digits beyond the country's longest number. The validator checks the number against the libphonenumber length and pattern for each type, and you can accept only some types, for example mobile numbers.
A value object. PhoneValue holds the country, the national number, e164, isValid, numberType (mobile, fixedLine, fixedLineOrMobile, tollFree and others), formatNational() and formatInternational().
A searchable country picker. As a dialog or a bottom sheet. Search matches English, French and Arabic names, ignoring case, accents and harakat. It also matches CLDR alternative names (Ivory Coast, Czech Republic), ISO codes and dial codes (+213, 213, +٢١٣). You can pin favorites at the top and restrict the list with an allow-list.
Arabic-Indic and Persian digits. ٠٥٥٥ and ۰۵۵۵ are accepted and converted to ASCII.
RTL. In a right-to-left app the country button moves to the right, while the number itself stays left-to-right.
Localized. Built-in texts and country names in English, French and Arabic, picked from the app locale. You can pass your own PhoneInputStrings.
Semantics labels. On the country button ("Change country. Current: Algeria +213"), on the picker rows ("France +33") and on the picker route.
How to use it
Add it from GitHub:
dependencies:
intl_phone_input:
git: https://github.com/AbdeldjalilChougui/intl_phone_input
Inside a form:
import 'package:flutter/material.dart';
import 'package:intl_phone_input/intl_phone_input.dart';
class SignUpForm extends StatefulWidget {
const SignUpForm({super.key});
@override
State<SignUpForm> createState() => _SignUpFormState();
}
class _SignUpFormState extends State<SignUpForm> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: [
IntlPhoneInput(
initialCountryCode: 'DZ',
favorites: const ['DZ', 'FR', 'MA', 'TN'],
decoration: const InputDecoration(labelText: 'Phone'),
allowedTypes: const {PhoneType.mobile},
validator: (value) => value.isEmpty ? 'Required' : null,
onChanged: (value) => debugPrint(value.e164),
onSaved: (value) => debugPrint('saved ${value.e164}'),
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
}
},
child: const Text('Send'),
),
],
),
);
}
}
The parsing is also usable without any widget:
final value = PhoneValue.parse('+213 555 12 34 56');
value.country.isoCode; // 'DZ'
value.nationalNumber; // '555123456'
value.e164; // '+213555123456'
value.isValid; // true
value.numberType; // PhoneType.mobile
value.formatNational(); // '0555 12 34 56'
value.formatInternational(); // '+213 555 12 34 56'
PhoneValue.parse('06 12 34 56 78', country: 'FR').e164; // '+33612345678'
PhoneValue.parse('+7 701 234 5678').country.isoCode; // 'KZ'
To open the picker yourself, call showCountryPickerDialog or showCountryPickerSheet, or embed CountryPickerList.
The built-in texts follow Localizations.localeOf(context). To get the French and Arabic texts, add flutter_localizations and list the locales in your MaterialApp, as the example app does.
Migrating from intl_phone_field
Most code only needs new names, and the README has the full table. The main ones:
IntlPhoneField(...)becomesIntlPhoneInput(...).PhoneNumberbecomesPhoneValue.completeNumberbecomese164,numberbecomesnationalNumber(digits only, no trunk prefix), andcountryISOCodebecomescountry.isoCode.phone.isValidNumber(), which throws, becomesvalue.isValid, a bool.countries:takes ISO codes such as['DZ', 'FR'], and a newfavoriteslist pins countries at the top.validatoris synchronous:(PhoneValue) => String?. It runs onForm.validate()and receives empty values too, so it can report a required field.languageCodeis removed. The picker follows the app locale.- New:
pickerMode: CountryPickerMode.bottomSheetandallowedTypes: {PhoneType.mobile}.
Three behaviour changes to check. The text field shows the formatted national number, so if you read controller.text, use PhoneValue or digitsOnly() instead. onChanged also fires when the country changes, because the value changed. And a trunk prefix the user types stays visible (0555 12 34 56) and is removed in PhoneValue.nationalNumber.
Things to know
- The parser dependency is pinned.
phone_numbers_parseris pinned to>=9.0.26 <9.1.0. That package only exports parsing, formatting and validation, so the trunk prefix and the national formatting rules are read from its generated metadata, through one file,lib/src/metadata_bridge.dart. - As-you-type formatting is not a port of libphonenumber's. It applies the metadata's format rules to the digits typed so far. It is close to
AsYouTypeFormatter, but a few countries may group incomplete numbers differently. - Only
+and00mean international. Other exit codes, such as011from North America, are read as national digits. formatNational()adds the trunk prefix only when the metadata has a national prefix formatting rule for that number's format. Otherwise it returns the grouped national number without a prefix.- Flags are emoji. Windows desktop and some web fonts show them as two letters.
- Three bundled languages. Country names and strings are in English, French and Arabic. Other locales get English names unless you pass your own
PhoneInputStrings. - The phone metadata comes from Google's libphonenumber, as packaged in
phone_numbers_parser, which is a runtime dependency and not a copy. - The country names come from Unicode CLDR, release 48.2.2, under the Unicode License v3.
Why I built it
The README lists the intl_phone_field issues this package addresses, and each one has a test. They show what goes wrong when phone data is kept by hand: wrong dial codes and lengths for some countries, a UK number validated as Guernsey, a national number that starts with the same digits as the dial code and gets cut short.
Others are form behaviour: the cursor jumping while editing, a validator that did not run on submit or when the field was empty, readOnly still opening the picker, initialCountryCode: '+91' being ignored.
Two decisions fix most of the list. First, dial codes, lengths and patterns come from libphonenumber instead of a hand-written table. Second, the field is a plain FormField, so the validator runs when Form.validate() runs and re-runs when the country changes.
On top of that I added what a form in Arabic or French needs: a picker that searches in three languages, Arabic-Indic digits, and a layout that behaves in RTL.
Get the code
The source, the README with the full migration table and the list of addressed issues, the example app and the tests are on GitHub: https://github.com/AbdeldjalilChougui/intl_phone_input.
It's MIT licensed, and the bundled CLDR data is under the Unicode License v3. Issues and pull requests are welcome.
Originally published at abdeldjalilchougui.biz.
Comments
No comments yet. Start the discussion.