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

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

Country Picker Plus 🌎

一个用于展示国家、州和城市的Flutter插件,你可以根据选择的结果来显示这些信息。你还可以在全球范围内搜索国家、州和城市。

示例 1 示例 2 示例 3 示例 4
image image image image

开始使用

步骤一: 请在你的项目依赖中添加yjy_country_picker_plus包:

flutter pub add yjy_country_picker_plus

步骤二: 在你需要使用的文件中导入相应的包:

import 'package:yjy_country_picker_plus/yjy_country_picker_plus.dart';

如何使用

该插件提供了两个方法供你根据需求使用。

  1. 使用主包,创建默认的三个字段(国家、州、城市),并可以按需自定义它们。

    示例代码:

    CountryPickerPlus(
      isRequired: true,
      countryLabel: "Country",
      countrySearchHintText: "Search Country",
      countryHintText: "Tap to Select Country",
      stateLabel: "State",
      stateHintText: "Tap to Select State",
      cityLabel: "City",
      cityHintText: "Tap to Select City",
      bottomSheetDecoration: bottomSheetDecoration,
      decoration: fieldDecoration,
      searchDecoration: searchDecoration,
      onCountrySaved: (value) {},
      onCountrySelected: (value) {},
      onStateSelected: (value) {},
      onCitySelected: (value) {},
    ),
    

    注意: 可以隐藏所有字段,直到前一个字段被选择。

    例如,在主包类中,使用以下属性:

    hideFields: true,
    
  2. 或者单独使用每个字段(country, state, city)。

    示例代码:

    CountryPickerPlus.country(...);
    
    CountryPickerPlus.state(country:'COUNTRY_NAME',....);
    
    CountryPickerPlus.city(country:'COUNTRY_NAME',state:'STATE_NAME',...);
    

    还有其他功能可以通过代码进行操作…

额外信息

该插件由Ali Hosseini开发。

如发现任何问题,请通过Github仓库报告: https://github.com/real-ali/country_picker_plus/issues


示例代码

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

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      home: CounteyPickerPlusView(),
    ),
  );
}

class CounteyPickerPlusView extends StatelessWidget {
  CounteyPickerPlusView({super.key});

  final _formKey = GlobalKey<FormState>();

  void _onSubmit() {
    if (_formKey.currentState?.validate() == true) {
      _formKey.currentState?.save();
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    var fieldDecoration = CPPFDecoration(
      labelStyle: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500),
      hintStyle: const TextStyle(fontSize: 12, fontWeight: FontWeight.w400),
      margin: const EdgeInsets.all(10),
      suffixColor: Colors.deepOrangeAccent,
      innerColor: Colors.deepOrangeAccent.withOpacity(0.06),
      filled: true,
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(10),
        borderSide: const BorderSide(color: Colors.deepOrangeAccent),
      ),
      errorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(10),
        borderSide: const BorderSide(color: Colors.red),
      ),
      border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(10),
        borderSide: BorderSide(color: Colors.deepOrangeAccent.withOpacity(0.2)),
      ),
    );

    final bottomSheetDecoration = CPPBSHDecoration(
      closeColor: Colors.deepOrangeAccent,
      itemDecoration: BoxDecoration(
        color: Colors.grey.withOpacity(0.03),
        borderRadius: BorderRadius.circular(8),
      ),
      itemsPadding: const EdgeInsets.all(8),
      itemsSpace: const EdgeInsets.symmetric(vertical: 4),
      itemTextStyle: const TextStyle(
        fontSize: 14,
        fontWeight: FontWeight.w400,
      ),
      shape: RoundedRectangleBorder(
        side: BorderSide(color: Colors.grey.withOpacity(0.1)),
        borderRadius: const BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
    );

    final searchDecoration = CPPSFDecoration(
      height: 45,
      padding: const EdgeInsets.symmetric(
        vertical: 2,
        horizontal: 10,
      ),
      filled: true,
      margin: const EdgeInsets.symmetric(vertical: 8),
      hintStyle: const TextStyle(
        color: Colors.white,
        fontWeight: FontWeight.w400,
      ),
      searchIconColor: Colors.white,
      textStyle: const TextStyle(color: Colors.white, fontSize: 12),
      innerColor: Colors.deepOrangeAccent,
      border: OutlineInputBorder(
        borderSide: BorderSide.none,
        borderRadius: BorderRadius.circular(10),
      ),
      focusedBorder: OutlineInputBorder(
        borderSide: BorderSide.none,
        borderRadius: BorderRadius.circular(10),
      ),
    );

    return Scaffold(
      persistentFooterButtons: [
        Container(
          margin: const EdgeInsets.all(20),
          width: double.infinity,
          height: 50,
          child: ElevatedButton(
              style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.deepOrangeAccent,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30))),
              onPressed: _onSubmit,
              child: const Text("提交数据")),
        )
      ],
      appBar: AppBar(
        backgroundColor: Colors.deepOrangeAccent,
        title: const Text("国家选择器增强版"),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          children: [
            CountryPickerPlus(
              // hideFields: true,
              isRequired: true,
              countryLabel: "Country",
              countrySearchHintText: "Search Country",
              countryHintText: "Tap to Select Country",
              stateLabel: "State",
              stateHintText: "Tap to Select State",
              cityLabel: "City",
              cityHintText: "Tap to Select City",
              bottomSheetDecoration: bottomSheetDecoration,
              decoration: fieldDecoration,
              searchDecoration: searchDecoration,
              textEditingControllerContry: TextEditingController(),
              textEditingControllerState: TextEditingController(),
              textEditingControllerCity: TextEditingController(),
              onCountrySaved: (value) {
                print(value);
              },
              onCitySaved: (value) {
                print(value);
              },
              onStateSaved: (value) {
                print(value);
              },
              onCountrySelected: (value) {
                print(value);
              },
              onStateSelected: (value) {
                print(value);
              },
              onCitySelected: (value) {
                print(value);
              },
            ),
          ],
        ),
      ),
    );
  }
}

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

1 回复

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


yjy_country_picker_plus 是一个用于 Flutter 的国家选择器插件,它允许用户在应用中选择国家或地区。以下是如何使用 yjy_country_picker_plus 的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  yjy_country_picker_plus: ^版本号

然后,运行 flutter pub get 来获取依赖。

2. 导入包

在你的 Dart 文件中导入 yjy_country_picker_plus 包:

import 'package:yjy_country_picker_plus/yjy_country_picker_plus.dart';

3. 使用国家选择器

你可以使用 CountryPicker 小部件来显示国家选择器。以下是一个简单的示例:

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Country? _selectedCountry;

  void _showCountryPicker() async {
    final country = await showCountryPicker(
      context: context,
      showPhoneCode: true, // 是否显示电话区号
      showWorldWide: true, // 是否显示“全球”选项
      showSearch: true, // 是否显示搜索框
    );
    setState(() {
      _selectedCountry = country;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Country Picker Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _selectedCountry != null
                ? Text('Selected Country: ${_selectedCountry!.name}')
                : Text('No country selected'),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _showCountryPicker,
              child: Text('Select Country'),
            ),
          ],
        ),
      ),
    );
  }
}

4. 运行应用

运行你的 Flutter 应用,你将看到一个按钮,点击按钮后会弹出一个国家选择器。选择一个国家后,_selectedCountry 将被更新,并在界面上显示所选国家的名称。

5. 自定义选项

yjy_country_picker_plus 提供了多个自定义选项,例如:

  • showPhoneCode: 是否显示电话区号。
  • showWorldWide: 是否显示“全球”选项。
  • showSearch: 是否显示搜索框。
  • countryListTheme: 自定义国家列表的主题。

你可以根据你的需求自定义这些选项。

6. 处理选择结果

showCountryPicker 方法返回一个 Country 对象,你可以从中获取国家的详细信息,如国家名称、代码、电话区号等。

if (_selectedCountry != null) {
  print('Country Name: ${_selectedCountry!.name}');
  print('Country Code: ${_selectedCountry!.code}');
  print('Phone Code: ${_selectedCountry!.phoneCode}');
}
回到顶部