Flutter国家选择器插件country_picker_flutter的使用

发布于 1周前 作者 wuwangju 来自 Flutter

Flutter国家选择器插件country_picker_flutter的使用

country_picker_flutter 是一个用于在 Flutter 应用程序中展示国家代码选择器的插件。它支持70种语言的国际化。

示例图片

使用方法

首先,你需要将 CountryCodePicker 组件添加到你的应用中,并设置 onChanged 回调。

import 'package:country_picker_flutter/country_code_picker.dart';
import 'package:flutter/material.dart';
import 'dart:developer';

@override
Widget build(BuildContext context) => new Scaffold(
  body: Center(
    child: CountryCodePicker(
      onChanged: print,
      // 初始选择和收藏可以是国家代码('IT')或区号('+39')
      initialSelection: 'IT',
      favorite: ['+39','PK'],
      // 只显示国家名称和旗帜
      showCountryOnly: false,
      // 关闭时只显示国家名称和旗帜
      showOnlyCountryWhenClosed: false,
      // 将旗帜和文本对齐到左侧
      alignLeft: false,
    ),
  ),
);

示例代码

以下是一个完整的示例,展示了如何在应用程序中使用 CountryCodePicker

import 'package:country_picker_flutter/country_code_picker.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('CountryPicker Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              CountryCodePicker(
                onChanged: print,
                // 初始选择和收藏可以是国家代码('IT')或区号('+39')
                initialSelection: 'IT',
                favorite: ['+39', 'FR'],
                countryFilter: ['IT', 'FR'],
                showFlagDialog: false,
                comparator: (a, b) => b.name!.compareTo(a.name!),
                // 获取初始选择的国家信息
                onInit: (code) => print("on init ${code!.name} ${code.dialCode} ${code.name}"),
              ),
              CountryCodePicker(
                onChanged: print,
                // 初始选择和收藏可以是国家代码('IT')或区号('+39')
                initialSelection: 'IT',
                favorite: ['+39', 'FR'],
                countryFilter: ['IT', 'FR'],
                // 标志可以通过 BoxDecoration 的 `borderRadius` 和 `shape` 字段进行样式设置
                flagDecoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(7),
                ),
              ),
              SizedBox(
                width: 400,
                height: 60,
                child: CountryCodePicker(
                  onChanged: print,
                  hideMainText: true,
                  showFlagMain: true,
                  showFlag: false,
                  initialSelection: 'TF',
                  hideSearch: true,
                  showCountryOnly: true,
                  showOnlyCountryWhenClosed: true,
                  alignLeft: true,
                ),
              ),
              SizedBox(
                width: 400,
                height: 60,
                child: CountryCodePicker(
                  onChanged: (e) => print(e.toLongString()),
                  initialSelection: 'TF',
                  showCountryOnly: true,
                  showOnlyCountryWhenClosed: true,
                  favorite: ['+39', 'FR'],
                ),
              ),
              SizedBox(
                width: 100,
                height: 60,
                child: CountryCodePicker(
                  enabled: false,
                  onChanged: (c) => c.name,
                  initialSelection: 'TF',
                  showCountryOnly: true,
                  showOnlyCountryWhenClosed: true,
                  favorite: ['+39', 'FR'],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

国际化(i18n)

要启用国际化功能,只需将 CountryLocalizations.delegate 添加到应用的委托列表中:

return new MaterialApp(
  supportedLocales: [
    Locale("af"),
    Locale("am"),
    Locale("ar"),
    Locale("az"),
    Locale("be"),
    Locale("bg"),
    Locale("bn"),
    Locale("bs"),
    Locale("ca"),
    Locale("cs"),
    Locale("da"),
    Locale("de"),
    Locale("el"),
    Locale("en"),
    Locale("es"),
    Locale("et"),
    Locale("fa"),
    Locale("fi"),
    Locale("fr"),
    Locale("gl"),
    Locale("ha"),
    Locale("he"),
    Locale("hi"),
    Locale("hr"),
    Locale("hu"),
    Locale("hy"),
    Locale("id"),
    Locale("is"),
    Locale("it"),
    Locale("ja"),
    Locale("ka"),
    Locale("kk"),
    Locale("km"),
    Locale("ko"),
    Locale("ku"),
    Locale("ky"),
    Locale("lt"),
    Locale("lv"),
    Locale("mk"),
    Locale("ml"),
    Locale("mn"),
    Locale("ms"),
    Locale("nb"),
    Locale("nl"),
    Locale("nn"),
    Locale("no"),
    Locale("pl"),
    Locale("ps"),
    Locale("pt"),
    Locale("ro"),
    Locale("ru"),
    Locale("sd"),
    Locale("sk"),
    Locale("sl"),
    Locale("so"),
    Locale("sq"),
    Locale("sr"),
    Locale("sv"),
    Locale("ta"),
    Locale("tg"),
    Locale("th"),
    Locale("tk"),
    Locale("tr"),
    Locale("tt"),
    Locale("uk"),
    Locale("ug"),
    Locale("ur"),
    Locale("uz"),
    Locale("vi"),
    Locale("zh")
  ],
  localizationsDelegates: [
    CountryLocalizations.delegate,
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
  ],
);

更多关于Flutter国家选择器插件country_picker_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter国家选择器插件country_picker_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用country_picker_flutter插件的一个详细代码示例。这个插件允许用户从列表中选择一个国家,并获取相关的国家信息,如国家代码、拨号代码等。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加country_picker_flutter依赖:

dependencies:
  flutter:
    sdk: flutter
  country_picker_flutter: ^0.2.0  # 请检查最新版本号

然后运行flutter pub get来安装依赖。

2. 导入插件

在你的Dart文件中导入插件:

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

3. 使用CountryPicker

下面是一个完整的示例,展示了如何在Flutter应用中使用CountryPicker

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Country Picker Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: CountryPickerScreen(),
    );
  }
}

class CountryPickerScreen extends StatefulWidget {
  @override
  _CountryPickerScreenState createState() => _CountryPickerScreenState();
}

class _CountryPickerScreenState extends State<CountryPickerScreen> {
  Country? selectedCountry;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Country Picker Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              selectedCountry != null
                  ? '${selectedCountry!.name} (+${selectedCountry!.phoneCode})'
                  : 'Select a country',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                final result = await showDialog(
                  context: context,
                  builder: (BuildContext context) {
                    return AlertDialog(
                      title: Text('Select a country'),
                      content: SingleChildScrollView(
                        child: CountryPicker(
                          onChanged: (Country country) {
                            setState(() {
                              selectedCountry = country;
                            });
                          },
                          favorite: ['+1', 'cn', 'in'], // 可选:设置默认显示的“收藏”国家代码
                          search: true, // 可选:启用搜索功能
                        ),
                      ),
                      actions: <Widget>[
                        TextButton(
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                          child: Text('Cancel'),
                        ),
                        TextButton(
                          onPressed: () {
                            if (selectedCountry != null) {
                              Navigator.of(context).pop(selectedCountry);
                            }
                          },
                          child: Text('OK'),
                        ),
                      ],
                    );
                  },
                );

                // 如果用户点击了“OK”按钮,result将包含所选国家
                if (result != null) {
                  // 这里可以进一步处理所选国家的信息
                  print('Selected country: ${result!.name} (+${result!.phoneCode})');
                }
              },
              child: Text('Select Country'),
            ),
          ],
        ),
      ),
    );
  }
}

代码解释

  1. 依赖添加:在pubspec.yaml中添加country_picker_flutter
  2. 导入插件:在需要使用插件的Dart文件中导入package:country_picker_flutter/country_picker.dart
  3. UI构建
    • 使用ElevatedButton触发对话框。
    • 在对话框中使用CountryPicker来显示国家列表。
    • 用户选择国家后,通过onChanged回调更新selectedCountry状态。
    • 用户点击“OK”按钮后,对话框返回所选国家对象。

这样,你就可以在Flutter应用中集成并使用country_picker_flutter插件来选择国家并获取相关信息了。

回到顶部