Flutterで国選択UIを実装する「country_picker」パッケージ

Flutterアプリを開発する中で、ユーザーに国を選択させたい場面はよくあります。例えば電話番号入力フォームや、住所登録の画面などです。

そういった場面で便利に使えるのが、country_pickerというパッケージです。今回は、このパッケージを使って簡単な国選択UIを作成する方法を紹介します。


1. パッケージの概要

country_pickerは、国名・国コード・国旗・電話コード(+81など)などを一覧から選べるUIを提供してくれるパッケージです。シンプルなUIで導入しやすく、カスタマイズも可能です。


2. インストール方法

まずは pubspec.yaml に以下を追加します。

dependencies:
  country_picker: ^2.0.22

その後、次のコマンドを実行します。

flutter pub get

3. 基本的な使い方

以下は、ボタンを押すと国の選択ダイアログが表示され、選択結果が画面に表示されるシンプルな例です。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CountryPickerExample(),
    );
  }
}

class CountryPickerExample extends StatefulWidget {
  @override
  _CountryPickerExampleState createState() => _CountryPickerExampleState();
}

class _CountryPickerExampleState extends State<CountryPickerExample> {
  Country? _selectedCountry;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Country Picker Example')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              _selectedCountry != null
                  ? '選択された国: ${_selectedCountry!.name} (${_selectedCountry!.countryCode})'
                  : '国が選択されていません',
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                showCountryPicker(
                  context: context,
                  showPhoneCode: true, // 電話コードも表示する
                  onSelect: (Country country) {
                    setState(() {
                      _selectedCountry = country;
                    });
                  },
                );
              },
              child: Text('国を選ぶ'),
            ),
          ],
        ),
      ),
    );
  }
}

4. よく使うオプション

showCountryPickerには、いくつか便利なオプションがあります。

showCountryPicker(
  context: context,
  favorite: ['JP', 'US'], // 上部に固定表示したい国
  showPhoneCode: true,
  countryListTheme: CountryListThemeData(
    backgroundColor: Colors.white,
    textStyle: TextStyle(fontSize: 16),
  ),
  onSelect: (Country country) {
    // 国が選ばれたときの処理
  },
);
  • favorite: 特定の国を上部に表示(例:日本、アメリカなど)
  • showPhoneCode: 電話コード(+81など)を表示
  • countryListTheme: テーマのカスタマイズ(背景色、文字サイズなど)

5. まとめ

country_pickerを使えば、手間のかかる国選択UIを簡単に実装できます。特に電話番号入力や、ユーザー登録の際に役立ちます。軽量でカスタマイズしやすい点も魅力です。

マッチしような要件がある際は、ぜひ一度使ってみてください。


参考リンク


タイトルとURLをコピーしました