country_state_city_pro 1.0.0
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.
import 'package:country_state_city_pro/country_state_city_pro.dart';
import 'package:material_ui/material_ui.dart';
void main() => runApp(const DemoApp());
/// Showcases the features of `country_state_city_pro`.
class DemoApp extends StatefulWidget {
const DemoApp({super.key});
@override
State<DemoApp> createState() => _DemoAppState();
}
class _DemoAppState extends State<DemoApp> {
ThemeMode _mode = ThemeMode.system;
/// `null` follows the device language.
Locale? _locale;
static const _languages = {
'en': 'English',
'fr': 'Français',
'es': 'Español',
'ar': 'العربية',
'bn': 'বাংলা',
'ja': '日本語',
};
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Country State City Pro',
debugShowCheckedModeBanner: false,
themeMode: _mode,
locale: _locale,
supportedLocales: [for (final code in _languages.keys) Locale(code)],
localizationsDelegates: GlobalMaterialLocalizations.delegates,
theme: ThemeData(colorSchemeSeed: Colors.indigo),
darkTheme: ThemeData(
colorSchemeSeed: Colors.indigo,
brightness: Brightness.dark,
),
home: DefaultTabController(
length: 5,
child: Scaffold(
appBar: AppBar(
title: const Text('Country State City Pro'),
actions: [
PopupMenuButton<String>(
tooltip: 'Language',
icon: const Icon(Icons.translate),
onSelected: (code) => setState(() => _locale = Locale(code)),
itemBuilder: (_) => [
for (final e in _languages.entries)
PopupMenuItem(value: e.key, child: Text(e.value)),
],
),
IconButton(
tooltip: 'Toggle dark mode',
icon: const Icon(Icons.brightness_6_outlined),
onPressed: () {
// This context is above MaterialApp, so read the resolved
// brightness from the mode and the platform, not Theme.
final dark =
_mode == ThemeMode.dark ||
(_mode == ThemeMode.system &&
MediaQuery.platformBrightnessOf(context) ==
Brightness.dark);
setState(
() => _mode = dark ? ThemeMode.light : ThemeMode.dark,
);
},
),
],
bottom: const TabBar(
isScrollable: true,
tabAlignment: TabAlignment.start,
tabs: [
Tab(text: 'Basic'),
Tab(text: 'Address form'),
Tab(text: 'Regions'),
Tab(text: 'Customized'),
Tab(text: 'Data'),
],
),
),
body: const TabBarView(
children: [
BasicDemo(),
AddressFormDemo(),
RegionsDemo(),
CustomizedDemo(),
DataDemo(),
],
),
),
),
);
}
}
/// The classic API: three text controllers receive the selected names.
class BasicDemo extends StatefulWidget {
const BasicDemo({super.key});
@override
State<BasicDemo> createState() => _BasicDemoState();
}
class _BasicDemoState extends State<BasicDemo> {
final _country = TextEditingController();
final _state = TextEditingController();
final _city = TextEditingController();
CityModel? _cityModel;
@override
void dispose() {
_country.dispose();
_state.dispose();
_city.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final city = _cityModel;
return ListView(
padding: const EdgeInsets.all(16),
children: [
CountryStateCityPicker(
country: _country,
state: _state,
city: _city,
favoriteCountries: const ['BD', 'IN', 'US'],
showClearButton: true,
onCityChanged: (c) => setState(() => _cityModel = c),
),
const SizedBox(height: 24),
ListenableBuilder(
listenable: Listenable.merge([_country, _state, _city]),
builder: (context, _) => Text(
[
_city.text,
_state.text,
_country.text,
].where((s) => s.isNotEmpty).join(', '),
style: Theme.of(context).textTheme.titleMedium,
),
),
if (city != null && city.hasCoordinates)
Text('Lat ${city.latitude}, Lng ${city.longitude}'),
if (city != null && city.isCustom) const Text('(typed by the user)'),
],
);
}
}
/// A full address form: picker, postal code and phone, with validation.
class AddressFormDemo extends StatefulWidget {
const AddressFormDemo({super.key});
@override
State<AddressFormDemo> createState() => _AddressFormDemoState();
}
class _AddressFormDemoState extends State<AddressFormDemo> {
final _formKey = GlobalKey<FormState>();
final _controller = CountryStateCityController();
final _postalCode = TextEditingController();
CscPhoneNumber? _phone;
String? _result;
@override
void dispose() {
_controller.dispose();
_postalCode.dispose();
super.dispose();
}
String? _required(String? value) =>
(value == null || value.isEmpty) ? 'Required' : null;
void _submit() {
if (!_formKey.currentState!.validate()) return;
final country = _controller.country!;
final state = _controller.state!;
final city = _controller.city!;
setState(() {
_result =
'${country.emoji} ${country.name} (${country.iso2}, '
'${country.currency})\n'
'${state.name} ${state.isoCode}\n'
'${city.name}${city.hasCoordinates ? ' @ ${city.latitude}, ${city.longitude}' : ''}\n'
'${_postalCode.text}\n'
'${_phone?.e164 ?? ''}';
});
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: ListView(
padding: const EdgeInsets.all(16),
children: [
CountryStateCityPicker(
controller: _controller,
showPhoneCode: true,
countryValidator: _required,
stateValidator: _required,
cityValidator: _required,
autovalidateMode: AutovalidateMode.onUserInteraction,
),
const SizedBox(height: 16),
// Rebuilds when the country changes, for its postal code format.
ListenableBuilder(
listenable: _controller,
builder: (context, _) {
final country = _controller.country;
return TextFormField(
controller: _postalCode,
decoration: InputDecoration(
labelText: 'Postal code',
hintText: country?.postalCodeFormat.replaceAll('#', '0'),
isDense: true,
border: const OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12)),
),
),
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: CscValidators.postalCode(country),
);
},
),
const SizedBox(height: 16),
// Follows the address country until a number is typed.
ListenableBuilder(
listenable: _controller,
builder: (context, _) => CscPhoneField(
initialCountry: _controller.country?.iso2,
favoriteCountries: const ['BD', 'IN', 'US'],
autovalidateMode: AutovalidateMode.onUserInteraction,
onChanged: (number) => _phone = number,
),
),
const SizedBox(height: 16),
Wrap(
spacing: 12,
runSpacing: 8,
children: [
FilledButton(onPressed: _submit, child: const Text('Submit')),
OutlinedButton(
onPressed: () => _controller.selectByName(
country: 'US',
state: 'California',
city: 'San Francisco',
),
child: const Text('Prefill'),
),
TextButton(
onPressed: () {
_controller.clear();
_postalCode.clear();
setState(() => _result = null);
},
child: const Text('Reset'),
),
],
),
if (_result != null) ...[const SizedBox(height: 16), Text(_result!)],
],
),
);
}
}
/// Administrative levels: regions vs provinces, grouping, typed-in states.
class RegionsDemo extends StatelessWidget {
const RegionsDemo({super.key});
@override
Widget build(BuildContext context) {
final heading = Theme.of(context).textTheme.titleSmall;
return ListView(
padding: const EdgeInsets.all(16),
children: [
Text('Italy by region (top level)', style: heading),
const SizedBox(height: 8),
const CountryStateCityPicker(
initialCountry: 'IT',
showCountry: false,
stateLevel: CscStateLevel.topLevel,
direction: Axis.horizontal,
),
const SizedBox(height: 32),
Text('Italian provinces grouped by region', style: heading),
const SizedBox(height: 8),
const CountryStateCityPicker(
initialCountry: 'IT',
showCountry: false,
groupStatesByRegion: true,
direction: Axis.horizontal,
),
const SizedBox(height: 32),
Text('Gibraltar has no states: type one', style: heading),
const SizedBox(height: 8),
const CountryStateCityPicker(initialCountry: 'GI'),
],
);
}
}
/// Fixed country, translations, custom styles and a horizontal layout.
class CustomizedDemo extends StatelessWidget {
const CustomizedDemo({super.key});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final heading = Theme.of(context).textTheme.titleSmall;
final decoration = InputDecoration(
filled: true,
fillColor: scheme.surfaceContainerHighest,
border: const OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.all(Radius.circular(16)),
),
isDense: true,
);
return ListView(
padding: const EdgeInsets.all(16),
children: [
Text('Country fixed to India, filled fields', style: heading),
const SizedBox(height: 8),
CountryStateCityPicker(
initialCountry: 'IN',
showCountry: false,
direction: Axis.horizontal,
textFieldDecoration: decoration,
showClearButton: true,
),
const SizedBox(height: 32),
Text('French labels, whatever the app language', style: heading),
const SizedBox(height: 8),
CountryStateCityPicker(
countryNameLocale: 'fr',
labels: CscLabels.forLocale(const Locale('fr')),
mode: CscPickerMode.centerDialog,
),
const SizedBox(height: 32),
Text('North America only, top dialog, custom styles', style: heading),
const SizedBox(height: 8),
CountryStateCityPicker(
countryFilter: const ['US', 'CA', 'MX'],
mode: CscPickerMode.dialog,
textStyle: TextStyle(
color: scheme.primary,
fontWeight: FontWeight.w600,
),
style: CscPickerStyle(
backgroundColor: scheme.primaryContainer,
itemTextStyle: TextStyle(
color: scheme.onPrimaryContainer,
fontSize: 17,
),
titleStyle: TextStyle(
color: scheme.onPrimaryContainer,
fontSize: 20,
fontWeight: FontWeight.bold,
),
searchDecoration: InputDecoration(
prefixIcon: const Icon(Icons.travel_explore),
filled: true,
fillColor: scheme.surface,
border: const OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12)),
borderSide: BorderSide.none,
),
),
highlightColor: scheme.primary.withValues(alpha: 0.12),
showDividers: true,
),
),
],
);
}
}
/// Currency and time zone pickers, nearest city, direct queries.
class DataDemo extends StatefulWidget {
const DataDemo({super.key});
@override
State<DataDemo> createState() => _DataDemoState();
}
class _DataDemoState extends State<DataDemo> {
final _controller = CountryStateCityController();
CurrencyModel? _currency;
CountryTimezone? _zone;
String _query = '';
static const _places = {
'Paris': (48.8566, 2.3522),
'Tokyo': (35.6762, 139.6503),
'Dhaka': (23.8103, 90.4125),
'Suva, Fiji': (-18.1248, 178.4501),
};
@override
void dispose() {
_controller.dispose();
super.dispose();
}
Future<void> _lookup() async {
final repo = CountryStateCityRepository.instance;
final japan = await repo.findCountry('JP');
final states = await repo.getStates(japan!);
final tokyo = states.firstWhere(
(s) => s.name.startsWith('Tokyo'),
orElse: () => states.first,
);
final cities = await repo.getCities(tokyo);
if (!mounted) return;
setState(() {
_query =
'${japan.emoji} ${japan.name}: ${states.length} prefectures, '
'${cities.length} places in ${tokyo.name}, capital ${japan.capital}, '
'time zone ${japan.timezones.first}';
});
}
@override
Widget build(BuildContext context) {
final heading = Theme.of(context).textTheme.titleSmall;
final currency = _currency;
final zone = _zone;
return ListView(
padding: const EdgeInsets.all(16),
children: [
Text('Currency and time zone', style: heading),
const SizedBox(height: 8),
Wrap(
spacing: 12,
runSpacing: 8,
children: [
OutlinedButton.icon(
icon: const Icon(Icons.payments_outlined),
label: Text(
currency == null
? 'Currency'
: '${currency.code} ${currency.symbol}',
),
onPressed: () async {
final picked = await showCurrencyPicker(
context,
selected: _currency,
favorites: const ['USD', 'EUR', 'BDT'],
);
if (picked != null) setState(() => _currency = picked);
},
),
OutlinedButton.icon(
icon: const Icon(Icons.schedule),
label: Text(
zone == null ? 'Time zone' : '${zone.city} ${zone.gmtOffset}',
),
onPressed: () async {
final picked = await showTimezonePicker(
context,
selected: _zone,
);
if (picked != null) setState(() => _zone = picked);
},
),
],
),
const SizedBox(height: 32),
Text('Nearest city (e.g. from GPS)', style: heading),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (final MapEntry(key: name, value: (lat, lng))
in _places.entries)
ActionChip(
avatar: const Icon(Icons.my_location, size: 18),
label: Text(name),
onPressed: () => _controller.selectNearestCity(lat, lng),
),
],
),
const SizedBox(height: 12),
CountryStateCityPicker(controller: _controller),
const SizedBox(height: 32),
FilledButton.tonal(
onPressed: _lookup,
child: const Text('Query the data directly'),
),
const SizedBox(height: 12),
Text(_query),
],
);
}
}