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

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

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

canopas_country_picker 是一个简单且可定制的Flutter插件,用于从国家列表中选择国家或拨号代码,并支持搜索功能。以下是该插件的详细使用说明和一个完整的示例demo。

预览

Preview

如何使用

显示国家选择器底部表单

CountryCode? code = await showCountryCodePickerSheet(context: context);

显示国家选择器对话框

CountryCode? code = await showCountryCodePickerDialog(context: context);

将国家列表作为UI组件显示

CountryCodeSelector(
   onCountryCodeTap: (CountryCode code) {
      /// Specify country code tap event
   },
    //Note: Cannot provide both onCountryCodeTap and codeBuilder, as onCountryCodeTap will not work if you have provided codeBuilder.
)

通过Alpha-2代码获取国家代码

CountryCode code = CountryCode.getCountryCodeByAlpha2(
    countryAlpha2Code:"IN", // its case-insensitive you can use both IN or in
);

获取当前国家的Alpha-2代码

String countryAlpha2Code = await Alpha2CountryCode.getCurrentCountryCode();

CountryCode code = CountryCode.getCountryCodeByAlpha2(
  countryAlpha2Code: countryAlpha2Code,
);

使用 await Alpha2CountryCode.getCurrentCountryCode() 将基于IP位置返回当前国家的Alpha-2代码,数据来自’http://ip-api.com/json/’ API。

通过设备区域获取当前国家的Alpha-2代码

CountryCode code = CountryCode.getCountryCodeByAlpha2(
    countryAlpha2Code: WidgetsBinding.instance.platformDispatcher.locale.countryCode, 
    /// if you have context, use View.of(context).platformDispatcher.locale.countryCode
);

注意:WidgetsBindingView.of(context) 是由Flutter SDK提供的。

通过拨号代码获取国家代码

CountryCode code = CountryCode.getCountryCodeByDialCode(
    dialCode: "+91",
);

推荐使用Alpha-2代码而不是拨号代码,因为拨号代码可能被多个国家共享。

通过拨号代码获取多个国家代码

List<CountryCode> codes = CountryCode.getCountryCodesByDialCode(
    dialCode: "+47",
);

显示本地化国家名称

String? l10nCountryName = countryCode.localizedName("en");

自定义

可以通过 CustomizationBuilders 类来自定义每个部分:

customizationBuilders: CustomizationBuilders(
  codeBuilder: (CountryCode code) {
    // Return something to change the country list item UI.
    // Note: onCountryCodeTap will be overridden by codeBuilder in customizationBuilders.

   // If want to do some customization in default country code view, you can use
    return DefaultCountryCodeListItemView(
      onCountryCodeTap: () {},
      code: code,
      locale: 'US', // To show a localized country name,
    );
  },
  
  codeSeparatorBuilder: (BuildContext context, int index) {
    // Return something to add a separator between country codes.
    return const SizedBox(); // Default
  },
  
  countryListBuilder: (List<CountryCode> codes, ScrollController? controller) {
    // Return something to customize the country list
  },
  
  textFieldBuilder: (void Function(String)? filter) {
    // Return the search text field widget
    //
    // If you want to do some customization in the default text field, you can use
    return DefaultCountryCodeFilterTextField(
      filter: filter,
    );

    // Use filter(searchText); to update the country code list.
  },
),

Bug和反馈

对于bug、反馈、问题和讨论,请使用 Github Issues

致谢

Canopas Country Picker由Canopas团队拥有和维护。您可以在Twitter上关注我们@canopassoftware以获取项目更新和发布信息。我们定期发布新主题的博客,您可以在这里阅读:Canopas Blog

示例代码

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

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

void main() {
  runApp(const MaterialApp(home: CountryPickerDemo()));
}

TextStyle kTextStyle =
    const TextStyle(fontWeight: FontWeight.bold, fontSize: 20);

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

  @override
  State<CountryPickerDemo> createState() => _CountryPickerDemoState();
}

class _CountryPickerDemoState extends State<CountryPickerDemo> {
  CountryCode? countryCode;
  bool selected = false;
  late TextEditingController textEditingController;

  @override
  void initState() {
    textEditingController = TextEditingController();
    super.initState();
  }

  @override
  void dispose() {
    textEditingController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Padding(
          padding: const EdgeInsets.only(top: 100, left: 16.0),
          child: Center(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: textEditingController,
                        decoration: InputDecoration(
                          counter: countryCode != null
                              ? Text(countryCode!.name)
                              : null,
                          label: const Text("Select country"),
                          labelStyle: kTextStyle,
                          suffixIcon: !selected
                              ? const Icon(Icons.arrow_drop_down_rounded)
                              : const Icon(Icons.arrow_drop_up_rounded),
                          enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(8),
                              borderSide:
                                  const BorderSide(color: Colors.purple)),
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(8),
                              borderSide: const BorderSide(color: Colors.grey)),
                        ),
                        onTap: () async {
                          setState(() {
                            selected = !selected;
                          });
                          final code = await showPickerSheet(context);
                          setState(() {
                            if (code != null) {
                              textEditingController.text =
                                  "${code.dialCode}   ${code.name}";
                            }
                            selected = !selected;
                          });
                        },
                      ),
                    ),
                    PopupMenuButton<int>(
                        icon: const Icon(Icons.more_vert),
                        onSelected: (int value) async {
                          CountryCode? code;
                          switch (value) {
                            case 1:
                              code = await showCountryCodePickerSheet(
                                  context: context);
                              break;
                            case 2:
                              code = await showCountryCodePickerDialog(
                                  context: context);
                              break;
                            case 3:
                              code = await Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) =>
                                          const ShowCountryPickerPage()));
                          }
                          if (code != null) {
                            setState(() {
                              textEditingController.text =
                                  "${code!.dialCode}   ${code.name}";
                            });
                          }
                        },
                        itemBuilder: (context) => [
                              const PopupMenuItem(
                                value: 1,
                                child: Text("Show PickerSheet"),
                              ),
                              const PopupMenuItem(
                                value: 2,
                                child: Text("Show PickerDialogue"),
                              ),
                              const PopupMenuItem(
                                value: 3,
                                child: Text("Show PickerPage"),
                              ),
                            ]),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Future<CountryCode?> showPickerSheet(BuildContext context) async {
    return await showCountryCodePickerSheet(
      context: context,

      customizationBuilders: CustomizationBuilders(
          backgroundColor: () => Colors.teal.shade100,
          codeBuilder: (CountryCode code) {
            return DefaultCountryCodeListItemView(
              code: code,
              nameStyle: kTextStyle,
              onCountryCodeTap: () {
                setState(() {
                  textEditingController.text =
                  "${code.dialCode}   ${code.name}";
                });
                Navigator.pop(context);
              },
            );
          },
          codeSeparatorBuilder: (context, value) => const Divider(),
          textFieldBuilder: (value) {
            return DefaultCountryCodeFilterTextField(
                hintText: "Search", fillColor: Colors.blueGrey.shade300);
          }),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: CountryCodeSelector(
            onCountryCodeTap: (CountryCode countryCode) =>
                Navigator.pop(context, countryCode)),
      ),
    );
  }
}

这个示例展示了如何在应用中集成canopas_country_picker插件,包括显示国家选择器底部表单、对话框以及将国家列表作为UI组件显示等功能。希望这个示例能帮助你更好地理解和使用这个插件。


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

1 回复

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


当然,以下是如何在Flutter项目中使用canopas_country_picker插件的详细代码案例。

首先,确保你的Flutter环境已经设置好,并且你的项目已经创建。然后,你需要添加canopas_country_picker依赖到你的pubspec.yaml文件中:

dependencies:
  flutter:
    sdk: flutter
  canopas_country_picker: ^最新版本号  # 请替换为最新的版本号

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

接下来,在你的Flutter项目中,你可以按照以下步骤使用canopas_country_picker

  1. 导入插件

在你的Dart文件中(通常是main.dart或者一个具体的页面文件),导入canopas_country_picker

import 'package:canopas_country_picker/canopas_country_picker.dart';
import 'package:flutter/material.dart';
  1. 使用CountryPicker

下面是一个简单的例子,展示如何在一个页面上使用CountryPicker

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter 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>[
            CountryPicker(
              initialSelection: 'US', // 初始选择的国家代码
              favorite: ['US', 'CN', 'IN'], // 收藏的国家代码列表
              onChanged: (Country? country) {
                setState(() {
                  selectedCountry = country;
                });
              },
              onSelected: (Country country) {
                // 当用户选择一个国家后的回调
                print('Selected country: ${country.name}');
              },
              searchCursorColor: Colors.blue,
              searchDecoration: InputDecoration(
                prefixIcon: Icon(Icons.search),
                border: OutlineInputBorder(),
                labelText: 'Search for a country',
              ),
              itemBuilder: (BuildContext context, Country country) {
                return ListTile(
                  leading: CircleAvatar(
                    backgroundImage: NetworkImage(country.flagUri),
                  ),
                  title: Text(country.name),
                  subtitle: Text(country.dialCode),
                );
              },
            ),
            SizedBox(height: 20),
            if (selectedCountry != null)
              Text(
                'Selected Country: ${selectedCountry!.name} (${selectedCountry!.dialCode})',
                style: TextStyle(fontSize: 20),
              ),
          ],
        ),
      ),
    );
  }
}

在这个例子中:

  • CountryPicker小部件用于显示国家选择器。
  • initialSelection参数设置了初始选择的国家代码。
  • favorite参数设置了一个收藏的国家代码列表。
  • onChanged回调在用户改变选择时触发。
  • onSelected回调在用户完成选择后触发。
  • searchCursorColorsearchDecoration用于自定义搜索框的样式。
  • itemBuilder用于自定义每个国家项的显示样式。

这个代码案例提供了一个完整的Flutter页面,展示了如何使用canopas_country_picker插件来选择国家,并显示选中的国家信息。你可以根据需要进行进一步的自定义和扩展。

回到顶部