Flutter国家信息选择插件country_info_picker的使用

Flutter国家信息选择插件country_info_picker的使用

pub package

一个用于从列表中选择国家的Flutter插件,具有国家名称、国旗、拨号代码、国家代码、国籍以及手机号码最大长度等功能。

Country Info Picker

特性

  • 显示国家国旗。
  • 显示国家拨号代码。
  • 显示国家代码。
  • 显示国家名称。
  • 显示国籍。
  • 显示手机号码最大长度。
  • 从列表中选择国家。
  • 获取所选国家的信息。

开始使用

pubspec.yaml文件中添加插件:

dependencies:
  country_info_picker: ^0.0.1

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

import 'package:country_info_picker/country_info_picker.dart';

使用CountryInfoPicker小部件:

CountryInfoPicker(
  onChanged: (CountryInfoModel country) {
    print('Select country: ${country.toLongString()}');
  },
);

示例

以下是一个完整的示例代码,展示了如何在应用中使用country_info_picker插件:

import 'package:flutter/material.dart';
import 'package:country_info_picker/country_info_picker.dart';
import 'package:flutter/services.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Country Info Picker Example',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  CountryInfoModel? selectedCountry;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text("Country Info Picker"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Selected Country: ${selectedCountry?.name ?? 'None'}',
              style: Theme.of(context).textTheme.headline6,
            ),

            // 选择国家代码并输入手机号码
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 35),
              child: IntrinsicHeight(
                child: Row(
                  children: [
                    Expanded(
                      flex: 2,
                      child: CountryInfoPicker(
                        favorite: const ['+20', '+966'],
                        initialSelection: 'EG',
                        onChanged: (CountryInfoModel value) {
                          setState(() {
                            selectedCountry = value;
                          });
                        },
                      ),
                    ),
                    const SizedBox(width: 10),
                    Expanded(
                      flex: 7,
                      child: TextFormField(
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                          LengthLimitingTextInputFormatter(selectedCountry?.maxLength),
                        ],
                        keyboardType: TextInputType.phone,
                        decoration: InputDecoration(
                          hintText: selectedCountry?.hintPhone,
                          labelText: "Mobile Number *",
                          prefixIcon: const Icon(
                            Icons.phone,
                            color: Colors.deepPurple,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),

            // 选择你的国家
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10),
              child: CountryInfoPicker(
                countryPickerType: CountryPickerType.CountryOnly,
                floatingLabelAlignment: FloatingLabelAlignment.start,
                suffixIcon: const Icon(
                  FontAwesomeIcons.chevronDown,
                  color: Color.fromRGBO(51, 71, 96, 0.4),
                  size: 17,
                ),
                favorite: const ['SA', 'EG'],
                onChanged: (CountryInfoModel value) {
                  // 可以在这里处理选择的国家
                },
              ),
            ),

            // 选择你的国籍
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10),
              child: CountryInfoPicker(
                countryPickerType: CountryPickerType.NationalityOnly,
                floatingLabelAlignment: FloatingLabelAlignment.start,
                suffixIcon: const Icon(
                  FontAwesomeIcons.chevronDown,
                  color: Color.fromRGBO(51, 71, 96, 0.4),
                  size: 17,
                ),
                favorite: const ['SA', 'EG'],
                onChanged: (CountryInfoModel value) {
                  // 可以在这里处理选择的国籍
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用country_info_picker插件的示例代码。这个插件可以帮助用户选择一个国家,并获取该国家的详细信息,比如国旗、电话代码、货币等。

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加country_info_picker依赖:

dependencies:
  flutter:
    sdk: flutter
  country_info_picker: ^latest_version  # 请替换为最新版本号

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

2. 导入插件

在你的Flutter项目的Dart文件中导入插件:

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

3. 使用CountryInfoPicker

下面是一个完整的示例,展示如何使用CountryInfoPicker来选择国家并显示选中的国家信息:

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Country Info Picker Example'),
        ),
        body: Center(
          child: CountryInfoPickerExample(),
        ),
      ),
    );
  }
}

class CountryInfoPickerExample extends StatefulWidget {
  @override
  _CountryInfoPickerExampleState createState() => _CountryInfoPickerExampleState();
}

class _CountryInfoPickerExampleState extends State<CountryInfoPickerExample> {
  CountryInfo? selectedCountry;

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        ElevatedButton(
          onPressed: () async {
            final result = await CountryInfoPicker.showDialog(
              context: context,
              title: 'Select a Country',
              favorite: ['US', 'CN', 'IN'], // 可选:设置常用国家
              searchable: true, // 可选:允许搜索
              showFlag: true, // 可选:显示国旗
              showCurrency: true, // 可选:显示货币
              showDialCode: true, // 可选:显示拨号代码
              showLanguage: true, // 可选:显示语言
              showName: 'official', // 可选:显示官方名称 ('official', 'common', 'local')
            );

            if (result != null) {
              setState(() {
                selectedCountry = result;
              });
            }
          },
          child: Text('Select Country'),
        ),
        if (selectedCountry != null) {
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Name: ${selectedCountry?.name}'),
                Text('Dial Code: +${selectedCountry?.dialCode}'),
                Text('Currency: ${selectedCountry?.currencyCode}'),
                Image.network(selectedCountry?.flag ?? ''),
              ],
            ),
          ),
        },
      ],
    );
  }
}

4. 运行应用

保存上述代码并运行你的Flutter应用。你应该会看到一个按钮,点击后会弹出一个对话框,允许你选择一个国家。选择国家后,应用会显示所选国家的名称、拨号代码、货币代码和国旗。

注意事项

  • 确保你的Flutter环境已经正确配置。
  • 在实际项目中,你可能需要根据UI设计调整按钮和文本的样式。
  • 插件的API可能会随着版本更新而变化,请参考插件的官方文档获取最新信息。

希望这个示例代码能够帮助你更好地理解和使用country_info_picker插件!

回到顶部