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

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

国家选择器小部件

Country Selector Widget 是一个由 Dart 和 Flutter 编写的国家选择器组件。它支持三种语言(英语、简体中文和繁体中文),实现了懒加载和淡入动画效果。此插件提供了 CountrySelectorWidgetshowCountrySelectorBottomSheet 来满足不同的需求。

支持平台

Android iOS Linux macOS Web Windows
支持 Any Any Any Any Any Any

使用示例

要查看设备或模拟器上的动画示例,请执行以下命令:

cd example/
flutter run

使用方法

要使用此插件,在项目的 pubspec.yaml 文件中添加 country_selector_widget 作为依赖项。

dependencies:
  country_selector_widget: ^版本号

示例

以下是使用 CountrySelectorWidgetshowCountrySelectorBottomSheet 的示例。

CountrySelectorWidget 的用法

示例代码

CountrySelectorWidget(
    onSelectedCountry: (Country country) async {
        // 选中国家后的回调函数
    },
)

showCountrySelectorBottomSheet 的用法

示例代码

showCountrySelectorBottomSheet(
    context: context,
    onSelectedCountry: (Country country) async {
        // 选中国家后的回调函数
    };
)

参数说明

参数 描述
withDialCode 是否显示国家的拨号代码
refCountryCode 设置默认选中的国家
customAppBar 设置自定义的 AppBar,而不是使用默认的 AppBar
bottomAppBarHeight 设置底部“继续”部分的高度
continueBtnPadding 设置底部“继续”部分与“继续”按钮之间的间距
selectedLocale 设置默认标签的语言,有三种 SelectedLocaleSelectedLocale.enSelectedLocale.zhCHSelectedLocale.zhHK
showSelectedWidget 设置是否在列表视图中选中时显示 CountryCardWidget
aniDuration CountryCardWidget 淡入动画的持续时间
onSelectedCountry 当从列表视图和继续按钮点击选中国家时的回调函数
appBarText 替换 AppBar 的默认文本
searchText 替换搜索框的 hintText
selectedCountryText 替换已选国家卡片的标题
withoutMatchText 当搜索结果不匹配时的 hintText
continueBtnText 替换继续按钮的文本
textFieldTextStyle 设置搜索框文本样式
appBarTextStyle 设置 AppBar 文本样式
searchTextStyle 设置搜索框 hintText 文本样式
selectedCountryTextStyle 设置已选国家文本样式
withoutMatchTextStyle 设置搜索结果不匹配时的 hintText 文本样式
continueBtnTextStyle 设置继续按钮文本样式
focusedBorderColor 设置搜索框选中状态时的边框颜色
selectedCardColor 设置选中国家卡片的颜色
continueBtnBgColor 设置继续按钮的背景颜色
continueBtnOverlayColor 设置继续按钮的覆盖颜色
textFieldborderRadius 设置搜索框的圆角半径
continueBtnRadius 设置继续按钮的圆角半径

国家选择器小部件的演示 - Flutter Web

CountrySelectorWidget - SelectedLocale.zhCH

显示国家选择器底部弹出窗口的演示 - Flutter Web

showCountrySelectorBottomSheet - SelectedLocale.en

国家选择器小部件的演示 - Android

Demonstration of showCountrySelectorBottomSheet - Android

国家选择器小部件的演示 - iOS

Demonstration of showCountrySelectorBottomSheet - iOS

显示国家选择器底部弹出窗口的演示 - macOS

Demonstration of showCountrySelectorBottomSheet - MacOS

MIT 许可证

Copyright (c) 2022 hkk97

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

完整示例代码

import 'package:flutter/material.dart';
import 'package:country_selector_widget/country_selector.dart';

void main() {
  runApp(
    MaterialApp(
      title: 'Country Selector Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const App(title: 'Country Selector Demo Page'),
    ),
  );
}

class App extends StatelessWidget {
  const App({super.key, required this.title});
  final String title;

  Future<void> showSuccessDialog(
    BuildContext context,
    Country country,
  ) async {
    await showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text(
            '[onSelectedCountry]',
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
          content: Text('${country.toJson()}'),
          actions: <Widget>[
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text(
                'Close',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        centerTitle: true,
        title: const Text(
          "Country Selector Widget",
          style: TextStyle(
            color: Colors.black,
          ),
        ),
        actions: [
          GestureDetector(
            onTap: () async {
              // 显示国家选择器底部弹出窗口
              await showCountrySelectorBottomSheet(
                context: context,
                // 启用拨号代码而不是选中圆圈
                withDialCode: true,
                // 设置默认选中的国家
                refCountryCode: "HK",
                onSelectedCountry: (country) async {
                  // 弹出对话框以显示国家对象的信息
                  await showSuccessDialog(
                    context,
                    country,
                  );
                }, onBuilded: (){}, onClosed: (){},
              );
            },
            child: Center(
              child: Container(
                margin: const EdgeInsets.symmetric(horizontal: 10.0),
                padding: const EdgeInsets.symmetric(
                  vertical: 10.0,
                  horizontal: 10.5,
                ),
                color: Colors.grey.shade200,
                child: const Text(
                  "showBottomSheet",
                  style: TextStyle(
                    color: Colors.black,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          )
        ],
      ),
      body: CountrySelectorWidget(
        // 选择中文语言来标记文本而不是英文
        selectedLocale: SelectedLocale.zhCH,
        // 设置默认选中的国家
        refCountryCode: "hk",
        // 选中国家的回调函数
        onSelectedCountry: (country) async {
          // 弹出对话框以显示国家对象的信息
          await showSuccessDialog(
            context,
            country,
          );
        }, onBuilded: (){},
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter应用中使用country_selector_widget插件的一个代码示例。这个插件允许用户在列表中选择一个国家,并获取相关的国家信息,如国家代码、国旗等。

首先,确保你已经在pubspec.yaml文件中添加了country_selector_widget依赖:

dependencies:
  flutter:
    sdk: flutter
  country_selector_widget: ^latest_version # 请替换为实际的最新版本号

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

接下来,你可以在你的Flutter应用中使用这个插件。以下是一个完整的示例,展示了如何使用country_selector_widget

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

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

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

class CountrySelectorDemo extends StatefulWidget {
  @override
  _CountrySelectorDemoState createState() => _CountrySelectorDemoState();
}

class _CountrySelectorDemoState extends State<CountrySelectorDemo> {
  Country? selectedCountry;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Country Selector Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            CountrySelectorWidget(
              initialSelection: 'US', // 初始选择的国家代码
              favorite: ['US', 'CN', 'IN'], // 预选的收藏国家代码列表
              onChanged: (Country? country) {
                setState(() {
                  selectedCountry = country;
                });
              },
              onFavoriteChanged: (Country country, bool isFavorite) {
                // 处理收藏状态变化(如果需要)
                print('${country.name} is now ${isFavorite ? 'favorite' : 'not favorite'}');
              },
            ),
            SizedBox(height: 20),
            if (selectedCountry != null)
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text('Selected Country:', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                  Text('Name: ${selectedCountry!.name}'),
                  Text('Code: ${selectedCountry!.dialCode}'),
                  Text('Emoji: ${selectedCountry!.emoji}'),
                  SizedBox(height: 10),
                  Image.network(selectedCountry!.flagUri),
                ],
              ),
          ],
        ),
      ),
    );
  }
}

在这个示例中:

  1. 我们创建了一个Flutter应用,并在主屏幕上使用了CountrySelectorWidget
  2. CountrySelectorWidgetinitialSelection属性设置了初始选择的国家代码为’US’。
  3. favorite属性设置了一个预选的收藏国家代码列表。
  4. onChanged回调在用户选择国家时被调用,并更新selectedCountry状态。
  5. onFavoriteChanged回调在用户更改收藏状态时被调用(这里只是打印了信息,你可以根据需要处理)。
  6. 如果选择了国家,会在页面上显示国家的名称、代码、Emoji和国旗。

这个示例展示了如何使用country_selector_widget插件来创建一个国家选择器,并处理用户的选择和收藏状态变化。你可以根据实际需求进一步定制和扩展这个示例。

回到顶部