Flutter越南省份数据插件vietnam_provinces的使用

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

Flutter 越南省份数据插件 vietnam_provinces 的使用

简介

vietnam_provinces 是一个 Flutter 插件,用于管理越南的行政区划数据,包括省份、区县和社区。该插件的数据来源于 Vietnam Provinces Open API

特性

  • 获取省份、区县和社区数据。
  • 支持按名称或编码查询。
  • 轻量级且易于集成。

开始使用

1. 添加依赖

pubspec.yaml 文件中添加 vietnam_provinces 依赖:

dependencies:
  vietnam_provinces: ^1.0.2

2. 初始化数据

在应用启动时初始化插件数据:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await VietnamProvinces.initialize();
  runApp(const MyApp());
}

使用方法

获取省份或查询

final provinces = VietnamProvinces.getProvinces(code: 1);
// 或者
final provinces = VietnamProvinces.getProvinces(query: "Hà");

获取区县(按省份编码查询)

final districts = VietnamProvinces.getDistricts(
  provinceCode: 1,
  query: "Quận",
);

获取社区(按省份编码和区县编码查询)

final wards = VietnamProvinces.getWards(
  provinceCode: 1,
  districtCode: 10,
  query: "Phường",
);

示例代码

以下是一个完整的示例代码,展示了如何使用 vietnam_provinces 插件来选择省份、区县和社区。

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await VietnamProvinces.initialize();
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Vietnam Provinces Example',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const HomePage(),
    );
  }
}

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

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Province? selectedProvince;
  District? selectedDistrict;
  Ward? selectedWard;

  List<Province> filteredProvinces = [];
  List<District> filteredDistricts = [];
  List<Ward> filteredWards = [];

  @override
  void initState() {
    super.initState();
    filteredProvinces = VietnamProvinces.getProvinces();
  }

  void updateFilteredProvinces(String query) {
    selectedProvince = null;
    selectedDistrict = null;
    selectedWard = null;
    filteredWards = [];
    filteredDistricts = [];
    setState(() {
      filteredProvinces = VietnamProvinces.getProvinces(query: query);
    });
  }

  void updateFilteredDistricts(String query) {
    selectedDistrict = null;
    selectedWard = null;
    filteredWards = [];
    if (selectedProvince != null) {
      setState(() {
        filteredDistricts = VietnamProvinces.getDistricts(
          provinceCode: selectedProvince!.code,
          query: query,
        );
      });
    }
  }

  void updateFilteredWards(String query) {
    selectedWard = null;
    if (selectedDistrict != null) {
      setState(() {
        filteredWards = VietnamProvinces.getWards(
          provinceCode: selectedProvince!.code,
          districtCode: selectedDistrict!.code,
          query: query,
        );
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Vietnam Provinces Picker')),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            buildDropdownSection(
              title: "Select Province",
              hintText: "Search for a province",
              items: filteredProvinces.map((p) => p.name).toList(),
              onSearchChanged: updateFilteredProvinces,
              currentValueSelected: selectedProvince?.name,
              onItemSelected: (value) {
                setState(() {
                  selectedProvince =
                      filteredProvinces.firstWhere((p) => p.name == value);
                  selectedDistrict = null;
                  selectedWard = null;
                  filteredDistricts = VietnamProvinces.getDistricts(
                    provinceCode: selectedProvince!.code,
                  );
                });
              },
            ),
            if (selectedProvince != null)
              buildDropdownSection(
                title: "Select District",
                hintText: "Search for a district",
                items: filteredDistricts.map((d) => d.name).toList(),
                onSearchChanged: updateFilteredDistricts,
                currentValueSelected: selectedDistrict?.name,
                onItemSelected: (value) {
                  setState(() {
                    selectedDistrict =
                        filteredDistricts.firstWhere((d) => d.name == value);
                    selectedWard = null;
                    filteredWards = VietnamProvinces.getWards(
                      provinceCode: selectedProvince!.code,
                      districtCode: selectedDistrict!.code,
                    );
                  });
                },
              ),
            if (selectedDistrict != null)
              buildDropdownSection(
                title: "Select Ward",
                hintText: "Search for a ward",
                items: filteredWards.map((w) => w.name).toList(),
                onSearchChanged: updateFilteredWards,
                currentValueSelected: selectedWard?.name,
                onItemSelected: (value) {
                  setState(() {
                    selectedWard =
                        filteredWards.firstWhere((w) => w.name == value);
                  });
                },
              ),
            if (selectedWard != null)
              Padding(
                padding: const EdgeInsets.only(top: 16.0),
                child: Text(
                  "Selected: ${selectedProvince?.name} - ${selectedDistrict?.name} - ${selectedWard?.name}",
                  style: const TextStyle(fontWeight: FontWeight.bold),
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget buildDropdownSection({
    required String title,
    required String hintText,
    required List<String> items,
    required void Function(String query) onSearchChanged,
    required void Function(String selectedItem) onItemSelected,
    required String? currentValueSelected,
  }) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(title, style: const TextStyle(fontSize: 16)),
          const SizedBox(height: 8),
          TextField(
            decoration: InputDecoration(
              hintText: hintText,
              prefixIcon: const Icon(Icons.search),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8.0),
              ),
            ),
            onChanged: onSearchChanged,
          ),
          const SizedBox(height: 8),
          DropdownButtonFormField<String>(
            value: currentValueSelected,
            isExpanded: true,
            decoration: InputDecoration(
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8.0),
              ),
              contentPadding: const EdgeInsets.symmetric(horizontal: 12.0),
            ),
            items: items
                .map(
                  (item) => DropdownMenuItem(
                    value: item,
                    child: Text(item, overflow: TextOverflow.ellipsis),
                  ),
                )
                .toList(),
            onChanged: (value) {
              if (value != null) onItemSelected(value);
            },
          ),
        ],
      ),
    );
  }
}

贡献

我们欢迎贡献!如果您有功能建议、错误修复或改进意见,请随时提交问题或拉取请求。

反馈和问题

如果您有任何反馈或发现错误,请提交 issues

许可证

本项目采用 MIT 许可证。

Buy Me A Coffee

希望这个插件能帮助您更好地管理和使用越南的行政区划数据!


更多关于Flutter越南省份数据插件vietnam_provinces的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter越南省份数据插件vietnam_provinces的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用vietnam_provinces插件来获取越南省份数据的示例代码。

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

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

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

接下来,你可以在你的Dart文件中使用vietnam_provinces插件来获取越南省份的数据。以下是一个简单的示例,展示了如何获取并显示省份列表:

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

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

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

class VietnamProvincesScreen extends StatefulWidget {
  @override
  _VietnamProvincesScreenState createState() => _VietnamProvincesScreenState();
}

class _VietnamProvincesScreenState extends State<VietnamProvincesScreen> {
  List<Province> _provinces = [];

  @override
  void initState() {
    super.initState();
    _fetchProvinces();
  }

  Future<void> _fetchProvinces() async {
    final provincesData = await VietnamProvinces.getProvinces();
    setState(() {
      _provinces = provincesData;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Vietnam Provinces'),
      ),
      body: _provinces.isEmpty
          ? Center(child: CircularProgressIndicator())
          : ListView.builder(
              itemCount: _provinces.length,
              itemBuilder: (context, index) {
                final province = _provinces[index];
                return ListTile(
                  title: Text('${province.name} (${province.type})'),
                );
              },
            ),
    );
  }
}

在这个示例中,我们做了以下几件事:

  1. 导入必要的包:我们导入了flutter/material.dartvietnam_provinces/vietnam_provinces.dart
  2. 创建主应用MyApp是一个无状态组件,它定义了应用的主题和主页。
  3. 创建主页VietnamProvincesScreen是一个有状态组件,它负责获取和显示省份数据。
  4. 获取省份数据:在_fetchProvinces方法中,我们使用VietnamProvinces.getProvinces()异步获取省份数据,并在获取完成后更新状态。
  5. 显示省份列表:我们使用ListView.builder来构建省份列表。如果省份列表为空,则显示一个加载指示器。

这个示例展示了如何使用vietnam_provinces插件获取并显示越南的省份数据。你可以根据需要对代码进行进一步的修改和扩展。

回到顶部