Simplifying User Experience: Easy Country Selection in Flutter with Country Picker Widget

When it comes to developing mobile applications, user experience is paramount. One critical aspect of user interaction involves providing intuitive ways to select user-specific information, such as their country. In this tutorial, we'll guide you through the process of seamlessly integrating a Country Picker Widget into your Flutter application, making country selection a breeze for your users.

Why Use a Country Picker Widget?

Selecting a user's country is a common requirement in many applications, especially those with international audiences. However, manually entering or selecting a country from a long list can be cumbersome. A Country Picker Widget streamlines this process, enhancing the overall user experience.

Getting Started

Before we dive into the implementation, ensure you have Flutter installed on your system. If not, you can download it here.

Next, let's integrate the Country Picker Widget into your Flutter project.

Step 1: Adding the Package

In your pubspec.yaml file, add the country_pickers package to your dependencies:

dependencies:
  flutter:
    sdk: flutter
  country_picker: ^2.0.21

Then run flutter pub get to fetch the package.

Step 2: Importing the Package

In the file where you want to use the Country Picker, import the package:

import 'package:flutter/material.dart';
import 'package:country_picker/country_picker.dart';

Step 3: Implementing the Country Picker

Now, you can use the CountryPickerDialog widget to display the Country Picker. Here's an example of how you can integrate it into a form:

showCountryPicker(
  context: context,
  showPhoneCode: true, // optional. Shows phone code before the country name.
  onSelect: (Country country) {
    print('Select country: ${country.displayName}');
  },
);

Customization Options

The CountryPickerDialog widget provides various customization options, allowing you to tailor the appearance and behavior of the Country Picker to suit your application's design.

Complete Source Code

import 'package:flutter/material.dart';


import 'package:country_picker/country_picker.dart';
import 'package:flutter_localizations/flutter_localizations.dart';


void main() => runApp(MyApp());


class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Demo for country picker package',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      supportedLocales: const [
        Locale('en'),
        Locale('ar'),
        Locale('es'),
        Locale('de'),
        Locale('fr'),
        Locale('el'),
        Locale('et'),
        Locale('nb'),
        Locale('nn'),
        Locale('pl'),
        Locale('pt'),
        Locale('ru'),
        Locale('hi'),
        Locale('ne'),
        Locale('uk'),
        Locale('hr'),
        Locale('tr'),
        Locale('lv'),
        Locale('lt'),
        Locale('ku'),
        Locale('nl'),
        Locale('it'),
        Locale('ko'),
        Locale('ja'),
        Locale('id'),
        Locale.fromSubtags(
            languageCode: 'zh',
            scriptCode: 'Hans'), // Generic Simplified Chinese 'zh_Hans'
        Locale.fromSubtags(
            languageCode: 'zh',
            scriptCode: 'Hant'), // Generic traditional Chinese 'zh_Hant'
      ],
      localizationsDelegates: const [
        CountryLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      home: HomePage(),
    );
  }
}


class HomePage extends StatelessWidget {
  String countryname = '';
  HomePage({Key? key}) : super(key: key);


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('FlutterforGeeks')),
      body: Center(
        child: Column(
          children: [
            ElevatedButton(
              onPressed: () {
                showCountryPicker(
                  context: context,
                  //Optional.  Can be used to exclude(remove) one ore more country from the countries list (optional).
                  exclude: <String>['KN', 'MF'],
                  favorite: <String>['SE'],
                  //Optional. Shows phone code before the country name.
                  showPhoneCode: true,
                  onSelect: (Country country) {
                    print('Select country: ${country.displayName}');
                    countryname = country.displayName.toString();
                  },
                  // Optional. Sets the theme for the country list picker.
                  countryListTheme: CountryListThemeData(
                    // Optional. Sets the border radius for the bottomsheet.
                    borderRadius: const BorderRadius.only(
                      topLeft: Radius.circular(40.0),
                      topRight: Radius.circular(40.0),
                    ),
                    // Optional. Styles the search field.
                    inputDecoration: InputDecoration(
                      labelText: 'Search',
                      hintText: 'Start typing to search',
                      prefixIcon: const Icon(Icons.search),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: const Color(0xFF8C98A8).withOpacity(0.2),
                        ),
                      ),
                    ),
                    // Optional. Styles the text in the search field
                    searchTextStyle: const TextStyle(
                      color: Colors.blue,
                      fontSize: 18,
                    ),
                  ),
                );
              },
              child: const Text('Show country picker'),
            ),
          ],
        ),
      ),
    );
  }
}

Video Demo


Conclusion

With the Country Picker Widget, you can significantly enhance the user experience in your Flutter applications. By simplifying the process of selecting a country, you create a more user-friendly environment, especially for international audiences.

Remember to explore the official documentation for more advanced features and customization options.

Happy coding!


Description of the image

Related Posts