Flutter国家信息获取插件flutter_countries的使用

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

Flutter国家信息获取插件flutter_countries的使用

通过属性类型从包含250个国家的数据库中查询并获取国家详细信息。 TODO: 添加您的许可证。

  • 国家总数 : 250
  • 州/地区/市镇总数 : 4,979
  • 城市/城镇/区划总数 : 148,266

查看可用数据的使用方法。

注意 数据集使用 rootBundle.loadString() 在主隔离区中检索,并在转换为JSON对象之前。然而,JSON到对象的转换发生在新的隔离区中。如果您在查询时遇到任何UI卡顿(除了使用 .all 获取器外),可以尝试在主隔离区之外运行查询。

参考: 运行 rootBundle.loadString() 在主隔离区之外

数据源由以下提供: 国家州郡城市数据库

特性

  • 离线工作
  • 异步子串查询
  • 支持模糊搜索
  • 匹配并返回相似或精确结果

使用 - Countries

通过属性和子串检索国家列表。

import 'package:country/country.dart';

// 获取所有国家
await Countries.all;

// 通过首都获取国家
await Countries.byCapital(capital);

// 通过经纬度获取国家
await Countries.byCoords(longitude, latitude);

// 通过货币名称获取国家
await Countries.byCurrencyName(currencyName);

// 通过ID获取国家
await Countries.byId(id);

// 通过ISO2代码获取国家
await Countries.byIso2(iso2);

// 通过ISO3代码获取国家
await Countries.byIso3(iso3);

// 通过名称获取国家
await Countries.byName(name);

// 通过本地名称获取国家
await Countries.byNative(native);

// 通过数字代码获取国家
await Countries.byNumericCode(numericCode);

// 通过电话代码获取国家
await Countries.byPhoneCode(phoneCode);

// 通过区域获取国家
await Countries.byRegion(region);

// 通过子区域获取国家
await Countries.bySubRegion(subRegion);

// 通过时区缩写获取国家
await Countries.byTimeZoneAbbreviation(timeZoneAbbreviation);

// 通过时区GMT偏移量获取国家
await Countries.byTimeZoneGmtOffset(timeZoneGmtOffset);

// 通过时区GMT偏移名称获取国家
await Countries.byTimeZoneGmtOffsetName(gmtOffsetName);

// 通过时区名称获取国家
await Countries.byTimeZoneTzName(timeZoneTzName);

// 通过时区区名称获取国家
await Countries.byTimeZoneZoneName(zoneName);

// 通过顶级域名获取国家
await Countries.byTld(tld);

// 通过翻译获取国家
await Countries.byTranslation(translation);

使用 - States

通过属性和子串检索州列表。

import 'package:country/country.dart';

// 获取所有州
await States.all;

// 通过经纬度获取州
await States.byCoords(longitude, latitude);

// 通过国家代码获取州
await States.byCountryCode(countryCode);

// 通过国家ID获取州
await States.byCountryId(countryId);

// 通过国家名称获取州
await States.byCountryName(countryName);

// 通过ID获取州
await States.byId(id);

// 通过纬度获取州
await States.byLatitude(latitude);

// 通过经度获取州
await States.byLongitude(longitude);

// 通过名称获取州
await States.byName(name);

// 通过州代码获取州
await States.byStateCode(stateCode);

// 通过类型获取州
await States.byType(type);

使用 - Cities

通过属性和子串检索城市列表。

import 'package:country/country.dart';

// 获取所有城市
await Cities.all;

// 通过经纬度获取城市
await Cities.byCoords(longitude, latitude);

// 通过国家代码获取城市
await Cities.byCountryCode(countryCode);

// 通过国家名称获取城市
await Cities.byCountryName(countryName);

// 通过ID获取城市
await Cities.byId(id);

// 通过纬度获取城市
await Cities.byLatitude(latitude);

// 通过经度获取城市
await Cities.byLongitude(longitude);

// 通过名称获取城市
await Cities.byName(name);

// 通过州代码获取城市
await Cities.byStateCode(stateCode);

// 通过州ID获取城市
await Cities.byStateId(stateId);

// 通过州名称获取城市
await Cities.byStateName(stateName);

// 通过WikiData ID获取城市
await Cities.byWikiDataId(wikiDataId);

// 通过国家ID获取城市
await Cities.bycountryID(countryId);

更多关于Flutter国家信息获取插件flutter_countries的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter国家信息获取插件flutter_countries的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用Flutter国家信息获取插件flutter_countries的代码示例。这个插件可以帮助你获取国家列表、国家详细信息等。

首先,你需要在你的Flutter项目中添加flutter_countries依赖。打开你的pubspec.yaml文件,并在dependencies部分添加以下行:

dependencies:
  flutter:
    sdk: flutter
  flutter_countries: ^x.y.z  # 请替换为最新版本号

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

接下来,你可以在你的Flutter应用中使用这个插件。以下是一个简单的示例,展示如何获取并显示国家列表以及每个国家的详细信息。

主程序文件(main.dart

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

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

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

class CountriesScreen extends StatefulWidget {
  @override
  _CountriesScreenState createState() => _CountriesScreenState();
}

class _CountriesScreenState extends State<CountriesScreen> {
  List<Country> countries = [];

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

  void fetchCountries() async {
    // 获取所有国家信息
    List<Country> fetchedCountries = await FlutterCountries.getAllCountries();
    
    // 更新状态
    setState(() {
      countries = fetchedCountries;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Countries Example'),
      ),
      body: countries.isEmpty
          ? Center(child: CircularProgressIndicator())
          : ListView.builder(
              itemCount: countries.length,
              itemBuilder: (context, index) {
                Country country = countries[index];
                return ListTile(
                  title: Text(country.name.common!),
                  subtitle: Text('${country.cca2} - ${country.capital![0].name!}'),
                  trailing: IconButton(
                    icon: Icon(Icons.info),
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => CountryDetailScreen(country: country),
                        ),
                      );
                    },
                  ),
                );
              }),
    );
  }
}

class CountryDetailScreen extends StatelessWidget {
  final Country country;

  CountryDetailScreen({required this.country});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(country.name.common!),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Name: ${country.name.common!}'),
            Text('Code (2): ${country.cca2}'),
            Text('Code (3): ${country.cca3}'),
            Text('Capital: ${country.capital![0].name!}'),
            Text('Region: ${country.region!}'),
            Text('Subregion: ${country.subregion!}'),
            Text('Population: ${country.population!.toString()}'),
            // 根据需要添加更多字段
          ],
        ),
      ),
    );
  }
}

解释

  1. 依赖添加:在pubspec.yaml中添加flutter_countries依赖。
  2. 初始化数据:在CountriesScreeninitState方法中,调用FlutterCountries.getAllCountries()获取所有国家信息,并更新状态。
  3. 显示国家列表:使用ListView.builder来显示国家列表,每个ListTile显示国家名称、国家代码和首都信息,并有一个信息图标按钮用于导航到详细信息页面。
  4. 详细信息页面CountryDetailScreen页面显示选定国家的详细信息,如名称、代码、首都、区域、子区域和人口等。

这个示例展示了如何使用flutter_countries插件来获取和显示国家信息。你可以根据需求进一步扩展和修改这个示例。

回到顶部