Flutter中国城市选择器插件city_picker_china的使用

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

Flutter 中国城市地区选择器

数据源:

  • 百度地图行政区划 adcode 映射表 【更新至21年04月】

相比国家统计局的数据,此插件的优点包括:

  • 数据较新
  • 必定包含第三级地区
  • 包含港澳台数据

使用实例

void showCityPicker() {

  /// 基础用法
  showModalBottomSheet<CityResult>(context: context, builder: (_) => const CityPicker());

  /// 通过代码选择
  showModalBottomSheet<CityResult>(context: context, builder: (_) => const CityPicker.fromCode(code: code));

  /// 通过城市名称选择
  showModalBottomSheet<CityResult>(
      context: context, builder: (_) => const CityPicker.formName(province: province, city: city, county: county));
}

home

picker

完整示例代码

import 'package:city_picker_china/city_picker_china.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
      locale: const Locale('zh'),
      supportedLocales: const [Locale('zh'), Locale('en')],
      localizationsDelegates: GlobalMaterialLocalizations.delegates,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  final codeController = TextEditingController();
  final provinceController = TextEditingController();
  final cityController = TextEditingController();
  final countyController = TextEditingController();

  _TriggerMode _triggerMode = _TriggerMode.none;

  void _changeMode(_TriggerMode? mode) {
    if (mode == null || mode == _triggerMode) {
      return;
    }
    setState(() {
      _triggerMode = mode;
    });
  }

  Future<void> _invoke() async {
    late final WidgetBuilder builder;

    switch (_triggerMode) {
      case _TriggerMode.byCode:
        builder = (_) => CityPicker.fromCode(code: codeController.text.trim());
        break;
      case _TriggerMode.byCity:
        builder = (_) => CityPicker.fromName(
              province: provinceController.text.trim(),
              city: cityController.text.trim(),
              county: countyController.text.trim(),
            );
        break;
      case _TriggerMode.none:
        builder = (_) => const CityPicker();
        break;
    }

    final res = await showModalBottomSheet<CityResult>(
        context: context, builder: builder);

    if (res == null) {
      return;
    }

    codeController.text = res.code;
    provinceController.text = res.province;
    cityController.text = res.city ?? '';
    countyController.text = res.county ?? '';
  }

  [@override](/user/override)
  void dispose() {
    codeController.dispose();
    provinceController.dispose();
    cityController.dispose();
    countyController.dispose();
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      floatingActionButton: FloatingActionButton(
        onPressed: _invoke,
        tooltip: 'Invoke',
        child: const Icon(Icons.open_in_new),
      ),
      body: Column(
        children: <Widget>[
          ListTile(
            leading: const Text('Code'),
            title: TextField(
              textAlign: TextAlign.right,
              controller: codeController,
            ),
          ),
          ListTile(
            leading: const Text('Province'),
            title: TextField(
              textAlign: TextAlign.right,
              controller: provinceController,
            ),
          ),
          ListTile(
            leading: const Text('City'),
            title: TextField(
              textAlign: TextAlign.right,
              controller: cityController,
            ),
          ),
          ListTile(
            leading: const Text('County'),
            title: TextField(
              textAlign: TextAlign.right,
              controller: countyController,
            ),
          ),
          const Divider(),
          RadioListTile(
            title: const Text('无参数调用'),
            value: _TriggerMode.none,
            groupValue: _triggerMode,
            onChanged: _changeMode,
          ),
          RadioListTile(
            title: const Text('通过代码调用'),
            value: _TriggerMode.byCode,
            groupValue: _triggerMode,
            onChanged: _changeMode,
          ),
          RadioListTile(
            title: const Text('通过城市名称调用'),
            value: _TriggerMode.byCity,
            groupValue: _triggerMode,
            onChanged: _changeMode,
          ),
        ],
      ),
    );
  }
}

/// 触发模式枚举
enum _TriggerMode { byCode, byCity, none }

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

1 回复

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


当然,以下是如何在Flutter项目中集成和使用city_picker_china插件的详细步骤和代码示例。

1. 添加依赖

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

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

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

2. 导入插件

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

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

3. 使用CityPickerChina

以下是一个完整的示例,展示如何在Flutter应用中集成并使用CityPickerChina来选择中国城市:

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

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

class CityPickerDemo extends StatefulWidget {
  @override
  _CityPickerDemoState createState() => _CityPickerDemoState();
}

class _CityPickerDemoState extends State<CityPickerDemo> {
  String selectedProvince = "";
  String selectedCity = "";
  String selectedDistrict = "";

  void _selectCity() async {
    final result = await CityPickerChina.showPicker(
      context,
      title: '选择城市',
      locale: Locale('zh', 'CN'),  // 设置语言环境为中文
      initialSelected: _initialSelected(),
    );

    if (result != null && result.length == 3) {
      setState(() {
        selectedProvince = result[0];
        selectedCity = result[1];
        selectedDistrict = result[2];
      });
    }
  }

  List<String> _initialSelected() {
    // 初始选择(可选),例如:[“广东省”, “广州市”, “天河区”]
    return ["广东省", "广州市", "天河区"];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('City Picker China Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '选择的省份: $selectedProvince',
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 10),
            Text(
              '选择的城市: $selectedCity',
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 10),
            Text(
              '选择的区/县: $selectedDistrict',
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _selectCity,
              child: Text('选择城市'),
            ),
          ],
        ),
      ),
    );
  }
}

4. 运行应用

确保你的开发环境已经正确配置,然后运行你的Flutter应用。你应该会看到一个简单的界面,上面有三个文本字段显示当前选择的省份、城市和区/县,以及一个按钮用于打开城市选择器。

点击按钮后,会弹出一个城市选择器对话框,你可以选择不同的省份、城市和区/县。选择完成后,选择的结果会显示在文本字段中。

这个示例展示了如何集成和使用city_picker_china插件来选择中国城市。你可以根据需要进行进一步的定制和扩展。

回到顶部