Skip to main content

country_state_city_pro 1.0.0 copy "country_state_city_pro: ^1.0.0" to clipboard
country_state_city_pro: ^1.0.0 copied to clipboard

Searchable country, state and city picker with offline data for 250 countries and 160k+ cities: flags, ISO and phone codes, translations and latitude/longitude.

country_state_city_pro #

pub package

A searchable country → state → city picker for Flutter with offline data for 250 countries, 5,000+ states and 165,000+ cities. It includes ISO codes, phone codes, currencies, flags, translated country names and latitude/longitude, plus a phone number field, postal code validation, currency and time zone pickers and a nearest-city lookup.

Works on Android, iOS, web, macOS, Windows and Linux. Needs no network access or API key.

Country list State search Selected Customized
Country list State search Selected Customized

Features #

  • Three linked fields: picking a country loads its states, and picking a state loads its cities.
  • Search that ignores case and accents (mexico finds México). It also matches ISO codes and dialing codes (bd, +880).
  • Full models in callbacks: ISO2/ISO3, phone code, capital, currency, emoji flag, time zones, translations, and latitude/longitude for countries, states and cities.
  • Prefill by code or name (initialCountry: 'US'), or from text already in your controllers, for edit forms.
  • Fix the country (hide its field), restrict to a list of countries, and pin favorites on top.
  • Built-in labels in 12 languages that follow the app locale, every text overridable, and country names in 19 languages. Right-to-left layouts work.
  • Full styling: field decoration and text style, list colors, text styles, search box, drag handle, highlight, section headers, spacing and shape. Defaults follow your Theme, including dark mode.
  • Choose the state level (Bangladesh divisions or districts, Italian regions or provinces) or group states under region headers.
  • Optional clear buttons, and typed-in states for countries that have none.
  • Keyboard friendly on web and desktop: arrows, Page Up/Down, Enter, Esc.
  • Lists open in a bottom sheet that closes when dragged down, from the handle or from the list once it is scrolled to the top. It stays above the keyboard. A top dialog or a centered dialog is available with mode:. Fields can be laid out vertically or horizontally.
  • Form validation, typed-in cities when a place is missing, and a CountryStateCityController to read and set the selection from code.
  • CscPhoneField with a country dial-code prefix, and CscValidators.postalCode for address forms.
  • Standalone showCountryPicker, showStatePicker, showCityPicker, showCurrencyPicker and showTimezonePicker, and a CountryStateCityRepository for querying the data directly, including nearestCity(lat, lng).
  • Bring your own data: plug in a CscDataSource to load from your API.
  • Fast: each country's cities are a separate file loaded on demand, large files are decoded off the UI thread, results are cached, and lists are built lazily.

Getting started #

dependencies:
  country_state_city_pro: ^1.0.0
import 'package:country_state_city_pro/country_state_city_pro.dart';

Requires Flutter 3.47 or newer.

Usage #

Basic #

final country = TextEditingController();
final state = TextEditingController();
final city = TextEditingController();

CountryStateCityPicker(
  country: country,
  state: state,
  city: city,
)

The controllers receive the selected names. Code written for 0.0.x keeps working.

Full models and coordinates #

CountryStateCityPicker(
  onCountryChanged: (country) => print('${country?.emoji} ${country?.dialCode}'),
  onStateChanged: (state) => print(state?.isoCode), // e.g. US-CA
  onCityChanged: (city) {
    if (city != null && city.hasCoordinates) {
      print('${city.name}: ${city.latitude}, ${city.longitude}');
    }
  },
)

A small share of cities (older entries kept for coverage) and every typed-in city (city.isCustom) have no coordinates.

Prefill, fixed country, filters #

// Start on India and hide the country field.
CountryStateCityPicker(initialCountry: 'IN', showCountry: false)

// Only North America; Mexico pinned first.
CountryStateCityPicker(
  countryFilter: const ['US', 'CA', 'MX'],
  favoriteCountries: const ['MX'],
)

// Prefill an edit form from saved values.
CountryStateCityPicker(
  initialCountry: 'United States',
  initialState: 'California',
  initialCity: 'San Francisco',
)

In a form #

Form(
  key: formKey,
  child: CountryStateCityPicker(
    countryValidator: (v) => v!.isEmpty ? 'Required' : null,
    stateValidator: (v) => v!.isEmpty ? 'Required' : null,
    cityValidator: (v) => v!.isEmpty ? 'Required' : null,
  ),
)

Address form: postal code and phone #

CountryModel? country;

CountryStateCityPicker(
  onCountryChanged: (c) => setState(() => country = c),
);
TextFormField(
  decoration: InputDecoration(
    labelText: 'Postal code',
    hintText: country?.postalCodeFormat, // e.g. "#####-####"
  ),
  validator: CscValidators.postalCode(country),
);
CscPhoneField(
  initialCountry: 'US',
  onChanged: (phone) => print(phone.e164), // +14155550123
  validateLength: true,
);

The phone field's prefix opens the country list. Typing or pasting a number that starts with + switches the country.

States: level, regions, clear buttons #

CountryStateCityPicker(
  initialCountry: 'IT',
  // Italian regions instead of provinces; cities of every province in the
  // region are listed.
  stateLevel: CscStateLevel.topLevel,
  showClearButton: true,
)

// Provinces, listed under their region.
CountryStateCityPicker(initialCountry: 'IT', groupStatesByRegion: true)

Countries with no states (Gibraltar, Macao, Vatican City, ...) accept a typed state with allowCustomState (on by default), and the city list then offers the country's cities.

Controller #

final controller = CountryStateCityController();

CountryStateCityPicker(controller: controller);

await controller.selectByName(country: 'DE', state: 'Bavaria', city: 'Munich');
print(controller.city?.latitude);
controller.clear();

Styling #

CountryStateCityPicker(
  textStyle: const TextStyle(fontSize: 16, color: Colors.indigo),
  textFieldDecoration: const InputDecoration(
    filled: true,
    border: OutlineInputBorder(borderSide: BorderSide.none),
  ),
  style: CscPickerStyle(
    backgroundColor: Colors.white,
    borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
    titleStyle: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
    itemTextStyle: const TextStyle(color: Colors.black87),
    selectedItemColor: Colors.indigo.shade50,
    highlightColor: Colors.indigo.shade100, // keyboard highlight
    sectionHeaderStyle: const TextStyle(fontWeight: FontWeight.w700),
    dragHandleColor: Colors.indigo,
    searchDecoration: const InputDecoration(
      hintText: 'Find a place',
      prefixIcon: Icon(Icons.travel_explore),
    ),
    showDividers: true,
  ),
)

With no textFieldDecoration, fields get rounded outlines unless your theme sets an inputDecorationTheme border.

Translations #

Labels follow the app locale: English, Spanish, French, German, Portuguese, Arabic, Hindi, Bengali, Chinese, Japanese, Russian and Turkish are built in, and country names follow too. To fix a language or change a text:

CountryStateCityPicker(
  countryNameLocale: 'fr',
  labels: CscLabels.forLocale(const Locale('fr'))
      .copyWith(stateLabel: 'Région'),
)

Country names are available in ar, br, de, es, fa, fr, hi, hr, it, ja, ko, nl, pl, pt, pt-BR, ru, tr, uk and zh-CN.

Flags #

Flags are emoji on Android, iOS, macOS and Linux. Windows has no flag emojis, and Flutter web would have to download a large emoji font, so those platforms show a small ISO-code badge instead. To use image flags anywhere, pass a flagBuilder:

CountryStateCityPicker(
  flagBuilder: (context, country) => MyFlagImage(country.iso2),
)

Standalone lists #

final country = await showCountryPicker(context, showPhoneCode: true);
final state = await showStatePicker(context, country: country!);
final city = await showCityPicker(context, state: state!);
final currency = await showCurrencyPicker(context, favorites: const ['USD']);
final zone = await showTimezonePicker(context);

Querying the data #

final repo = CountryStateCityRepository.instance;
final japan = await repo.findCountry('JP');
final prefectures = await repo.getStates(japan!);
final cities = await repo.getCities(prefectures.first);

// Prefill from the device location.
final near = await repo.nearestCity(48.8566, 2.3522); // Paris
await controller.selectNearestCity(35.68, 139.69); // Tokyo

Your own data #

class MyApiSource extends CscDataSource {
  @override
  Future<List<CountryModel>> loadCountries() async => ...;
  @override
  Future<List<StateModel>> loadStates(CountryModel country) async => ...;
  @override
  Future<List<CityModel>> loadCities(
    CountryModel country,
    List<StateModel> states,
  ) async => ...;
}

final controller = CountryStateCityController(
  repository: CountryStateCityRepository(source: MyApiSource()),
);

Results are cached, so each method runs once per country.

Data #

The data comes from the countries-states-cities-database (release v5.2.0-export.1), © Darshan Gada and contributors, under the Open Database License. Cities from earlier versions of this package that the database lacks are kept, so no country lost coverage.

The state level is the subdivision that cities belong to: for example, provinces in Italy and districts in Bangladesh. When two entries share a name (Minsk city and Minsk region), the list shows their type. StateModel.parentId and parentName point to the larger region where one exists; use stateLevel: CscStateLevel.topLevel to pick those instead.

Found wrong or missing data? Please report it upstream to the database, or open an issue here. A monthly workflow opens a pull request when dr5hn publishes a new release; maintainers can also regenerate the assets with dart run tool/build_data.dart <download-dir> tool/legacy --version <tag>.

Migrating from 0.0.x #

  • Your code keeps compiling. The country, state and city controllers are now optional.
  • Fields now use labelText. Pass showFieldLabels: false to get the old hint-only look.
  • Lists open in a bottom sheet with no close button: drag it down or tap outside it. Pass mode: CscPickerMode.dialog to keep the 0.0.x panel that slides down from the top, or style: CscPickerStyle(showCloseButton: true) to keep the button.
  • The list follows your theme. Set dialogColor or CscPickerStyle to control colors explicitly.
  • The data is larger and more current. Some names changed to their official forms (for example "Distrito Federal" became "Ciudad de México").

License #

Code: MIT, see LICENSE. Data: ODbL 1.0, see doc/DATA_LICENSE.md.

65
likes
160
points
635
downloads
screenshot

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Searchable country, state and city picker with offline data for 250 countries and 160k+ cities: flags, ISO and phone codes, translations and latitude/longitude.

Repository (GitHub)
View/report issues

Topics

#country-picker #address #location #picker #form

License

MIT (license)

Dependencies

flutter, material_ui

More

Packages that depend on country_state_city_pro