How to make Country Picker and get Name Code Dial Code Flag on Flutter App
Introduction
Country picker is a crucial feature in many mobile applications, especially those that require user location or international calling. In this blog post, we will explore how to create a country picker in a Flutter app and retrieve the country name, code, dial code, and flag.
Creating the Country Picker
To create a country picker in Flutter, you can use the country_picker package. First, add the package to your pubspec.yaml file and run flutter pub get in your terminal. Then, import the package in your Dart file and create a CountryPicker widget.
“`dart
import ‘package:countrypicker/countrypicker.dart’;
CountryPicker(
onChanged: (Country country) {
print(country.name);
print(country.isoCode);
print(country.dialingCode);
},
onDismiss: () {
print(‘Dismissed’);
},
)
“`
Getting Country Information
Once a country is selected, you can retrieve its information using the country object. The country object contains properties such as name, isoCode, and dialingCode. You can also use the country.flag to display the country flag.
“`dart
CountryPicker(
onChanged: (Country country) {
String countryCode = country.isoCode;
String countryName = country.name;
String dialCode = country.dialingCode;
// Use the country information as needed
},
)
“`
Displaying the Country Flag
To display the country flag, you can use the country.flag property and pass it to an Image.asset constructor.
“`dart
Image.asset(
country.flag,
package: ‘country_picker’,
)
“`
Using a Custom Country List
If you want to use a custom country list, you can create a list of Country objects and pass it to the CountryPicker widget.
“`dart
List
Country(
name: ‘United States’,
isoCode: ‘US’,
dialingCode: ‘+1’,
flag: ‘flags/us.png’,
),
// Add more countries to the list
];
CountryPicker(
countries: countries,
// …
)
“`
Conclusion
In this blog post, we have explored how to create a country picker in a Flutter app and retrieve the country name, code, dial code, and flag. By using the country_picker package, you can easily add this feature to your app.
Frequently Asked Questions
1. What is the country_picker package?
The country_picker package is a Flutter package that provides a country picker widget and a list of countries.
2. How do I use the country_picker package?
To use the country_picker package, add it to your pubspec.yaml file and run flutter pub get in your terminal.
3. Can I use a custom country list?
Yes, you can use a custom country list by creating a list of Country objects and passing it to the CountryPicker widget.
4. How do I display the country flag?
To display the country flag, use the country.flag property and pass it to an Image.asset constructor.
5. Is the country_picker package free?
Yes, the country_picker package is free and open-source.