country_provider 1.0.1

  • Readme
  • Changelog
  • Example
  • Installing
  • 80

country_provider Flutter Plugin Twitter URL GitHub stars GitHub forks #

pub package GitHub last commit GitHub pull requests GitHub closed pull requests GitHub issues GitHub closed issues Open Source Love

Country Provider is a flutter library wrapper around the API provided by REST Countries https://restcountries.eu (Get information about countries via a RESTful API)

Download App GitHub All Releases #

Getting Started #

1. Add library to your pubspec.yaml #


dependencies:
  country_provider: ^0.0.1

2. Import library in dart file #

import 'package:country_provider/country_provider.dart';

Note #

Each method return a List of Country.

Usage #

  • Get all countries.
// Get all countries
List<Country> countries = await CountryProvider.getAllCountries();
  • Search by country name. It can be the native name or partial name.
// Search by country name
List<Country> result = await CountryProvider.getCountriesByName("Ameri");

If partial name, this method could return a list of countries. Else a List of one element.

  • Search by country full name.
// Search by country full name
Country result = await CountryProvider.getCountryByFullname("India")?.first;
  • Search by ISO 3166-1 2-letter or 3-letter country code.
// Search by list of ISO 3166-1 2-letter or 3-letter country codes
Country result = await CountryProvider.getCountryByCode("Ind")?.first;
  • Search by list of ISO 3166-1 2-letter or 3-letter country codes.
// Search by list of ISO 3166-1 2-letter or 3-letter country codes
List<Country> result = CountryProvider.getCountriesByListOfCodes(["Ind", "col", "ru"]);
  • Search by ISO 4217 currency code.
// Search by ISO 4217 currency code
List<Country> result = await CountryProvider.getCountryByCurrencyCode("Inr")
  • Search by ISO 639-1 language code.
// Search by ISO 639-1 language code
List<Country> result = await CountryProvider.getCountriesByLanguageCode(["Hin","en",]);
  • Search by capital city.
// Search by capital city
var result = await CountryProvider.getCountryByCapitalCity("Delhi");

You can use var instead of explicit types. I use explicit types to show you the return type of each method.

  • Search by calling code.
// Search by calling code
List<Country> result = await CountryProvider.getCountryByCallingCode(91);
  • Search by continent: Africa, Americas, Asia, Europe, Oceania.
//  Search by continent: Africa, Americas, Asia, Europe, Oceania
List<Country> result = await CountryProvider.getcountryByRegionalBloc("Asia");
  • Search by regional bloc: EU, EFTA, CARICOM, AU, USAN, EEU, AL, ASEAN , CAIS, CEFTA , NAFTA , SAARC.
//  Search by regional bloc
List<Country> result = await CountryProvider.getCountriesByContinent("ASEAN");

EU (European Union), EFTA (European Free Trade Association), CARICOM (Caribbean Community), PA (Pacific Alliance), AU (African Union), USAN (Union of South American Nations), EEU (Eurasian Economic Union), AL (Arab League), ASEAN (Association of Southeast Asian Nations), CAIS (Central American Integration System), CEFTA (Central European Free Trade Agreement), NAFTA (North American Free Trade Agreement), SAARC (South Asian Association for Regional Cooperation).

Apply filters #

To get filtered country data pass CountryFilter model as argument in search countries method.

// Get all countries name only 
var countries = await CountryProvider.getAllCountries(filter: CountryFilter(isName: true));
List<string> countriesInSpanish = countries.map((e) => e.name).toList();

// Get all countries name only in Spanish
var countries = await CountryProvider.getAllCountries(filter: CountryFilter(isName: true));
List<string> countriesInSpanish = countries.map((e) => e.translations.es).toList();

// Get Europe countries in French language
var europeCountries = await CountryProvider.getcountryByRegionalBloc("Europe",filter: CountryFilter(isName: true));
List<string> europeCountriesInFrench = europeCountries.map((e) => e.translations.fr).toList();

// Get all countries name with their capital city only
var countries = await CountryProvider.getAllCountries(filter: CountryFilter(isName: true,isCapital:true));

// Get all countries name with country code and their capital city only
var countries = await CountryProvider.getAllCountries(filter: CountryFilter(isName: true,isCapital:true,isAlpha2Code:true,isAlpha3Code: true));


// Fell free to aplly filters 🤓

Default language for country name is English, but you can also get the name in other languages such as: de(German language), es(Spanish language), fr(French language), ja(Japanese language), it(Italian language), br(Breton language), pt(Portuguese language), nl(Dutch language), hr(Croatian language) and fa(Persian language).

Country class #

class Country
{	  
    // Get Country name
    String name;

    // Gets  Top Level Domain
    List<String> topLevelDomain;
    
    // Gets Alpha2 Code
    String alpha2Code;
    
    // Gets Alpha3 Code
    String alpha3Code;
    
    // Gets Calling Code
    List<String> callingCodes;
    
    // Gets Capital City
    String capital;
    
    // Get AltSpelling
    List<String> altSpellings;
    
    // Get Region
    String region;
    
    // Get SubDomain
    String subregion;
    
    // Get Population
    int population;
    
    // Get Latlng(Latitude and Longitude)
    List<double> latlng;
    
    // Get Demonym
    String demonym;
    
    // Get Area
    double area;
    
    // Get Gini
    double gini;
    
    // Get Timezone
    List<String> timezones;
    
    // Get Borders
    List<String> borders;
    
    // Get Native Name
    String nativeName;
    
    // Get Numeric Code
    String numericCode;
    
    // Get Currencies
    List<Currency> currencies;
    
     // Get Languages
    List<Language> languages;
    
    // Gets Translations
    Translations translations;
    
    // Get Flag
    String flag;
    
    // Get Regional Blocs
    List<RegionalBloc> regionalBlocs;
    
    // Get  Cioc(International Olympic Committee Code)
    String cioc;
}

CountryFilter Class #

class CountryFilter{
  bool isName;
  bool isCapital;
  bool isRegion;
  bool isAlpha2Code;
  bool isAlpha3Code;
  bool isDemonym;
  bool isTimeZone;
  bool isCallingCode;
  bool isBorders;
  bool isAltSpellings;
  bool isCurrency;
  bool isLanguage;
  bool isLatLong;
  bool isTranslation;
  bool isFlag;

  CountryFilter({
    this.isName = false,
    this.isCapital = false,
    this.isRegion = false,
    this.isAlpha2Code = false,
    this.isAlpha3Code = false,
    this.isDemonym = false,
    this.isTimeZone = false,
    this.isCallingCode = false,
    this.isBorders = false,
    this.isAltSpellings = false,
    this.isCurrency = false,
    this.isLanguage = false,
    this.isLatLong = false,
    this.isTranslation = false,
    this.isFlag = false,
  });
}

Credits #

Thanks to Fayder Florez for developing REST Countries API.

Flutter plugins #

Plugin NameStars
Empty widgetGitHub stars
Add ThumbnailGitHub stars
Filter List WidgetGitHub stars

Pull Requests #

I welcome and encourage all pull requests. It usually will take me within 24-48 hours to respond to any issue or request.

Created & Maintained By #

Sonu Sharma (Twitter) (Youtube) (Insta) Twitter Follow

If you found this project helpful or you learned something from the source code and want to thank me, consider buying me a cup of ☕

[1.0.0] - 30 May 2020 #

  • Added Domain, Numeric code, CISO, Lat long, Language name code and symbol
  • Added REgional blocks name, Countries name translation

[1.0.0] - 30 May 2020 #

  • Code refactor and documentation

[0.0.1] - 29 May 2020 #

  • Add countries search method
  • Add country data filter functionality

example/lib/main.dart

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Search Country Plugin Demo'),
    );
  }
}

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

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Country> _countryList;
  CountryFilter filter = CountryFilter();
  bool isLoading = false;

  void _searchCountry(int index) async {
    try {
      Navigator.pop(context);
      isLoading = true;
      setState(() {});
      switch (index) {
        case 0:
          _countryList =
              await CountryProvider.getAllCountries(filter: CountryFilter());
          break;
        case 1:
          _countryList = await CountryProvider.getCountriesByName("Ameri",
              filter: CountryFilter());
          break;
        case 2:
          _countryList = [
            await CountryProvider.getCountryByFullname("India",
                filter: CountryFilter())
          ];
          break;
        case 3:
          _countryList = [
            await CountryProvider.getCountryByCode("Ind",
                filter: CountryFilter())
          ];
          break;
        case 4:
          _countryList = await CountryProvider.getCountriesByListOfCodes(
              ["Ind", "col", "ru"],
              filter: CountryFilter());
          break;
        case 5:
          _countryList = await CountryProvider.getCountryByCurrencyCode("Inr",
              filter: CountryFilter());
          break;
        case 6:
          _countryList = await CountryProvider.getCountriesByLanguageCode([
            "Hin",
            "en",
          ], filter: CountryFilter());
          break;
        case 7:
          _countryList = await CountryProvider.getCountryByCapitalCity("Delhi",
              filter: CountryFilter());
          break;
        case 8:
          _countryList = await CountryProvider.getCountryByCallingCode(91,
              filter: CountryFilter());
          break;
        case 9:
          _countryList = await CountryProvider.getcountryByRegionalBloc("Asia",
              filter: CountryFilter());
          break;
        case 10:
          _countryList = await CountryProvider.getCountriesByContinent("ASEAN",
              filter: CountryFilter());
          break;

        default:
          break;
      }
      isLoading = false;
      setState(() {});

      print(_countryList.first.name);
    } catch (error) {
      print(error);
    }
  }

  void openSearchCountriesButton() async {
    await showModalBottomSheet(
        backgroundColor: Colors.transparent,
        context: context,
        isScrollControlled: true,
        builder: (context) => _countriesButton());
  }

  Widget _countriesButton() {
    return NotificationListener<DraggableScrollableNotification>(
      onNotification: (notification) {
        return true;
      },
      child: DraggableScrollableSheet(
        initialChildSize: .50,
        minChildSize: .3,
        builder: (BuildContext context, ScrollController scrollcontroller) {
          return Container(
            padding: EdgeInsets.only(top: 10),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(30),
                topRight: Radius.circular(30),
              ),
            ),
            child: Column(
              children: <Widget>[
                Container(
                  height: 5,
                  width: 50,
                  margin: EdgeInsets.symmetric(vertical: 10),
                  decoration: BoxDecoration(
                      color: Colors.grey.shade300,
                      borderRadius: BorderRadius.all(
                        Radius.circular(10),
                      )),
                  // child:Icon(Icons.drag_handle)
                ),
                Center(
                  child: Text(
                    "Select search option",
                    style: Theme.of(context)
                        .typography
                        .dense
                        .headline6
                        .copyWith(color: Colors.black),
                  ),
                ),
                SizedBox(
                  height: 16,
                ),
                Expanded(
                  child: ListView(
                    controller: scrollcontroller,
                    children: <Widget>[
                      _button("Search all countries", "", () {
                        _searchCountry(0);
                      }),
                      _button("Countries by name ", " Example: \"Ameri\"", () {
                        _searchCountry(1);
                      }),
                      _button("Country by full name  ", " Example: \"India\"",
                          () {
                        _searchCountry(2);
                      }),
                      _button("Country by code", " Example:  \"Ind\"", () {
                        _searchCountry(3);
                      }),
                      _button("Countries by list of code",
                          " Example: [Ind, Col,ru]", () {
                        _searchCountry(4);
                      }),
                      _button(
                          "Countries by currency code ", " Example: \"Inr\"",
                          () {
                        _searchCountry(5);
                      }),
                      _button("Countries by language code",
                          " Example: [en, hin,ru]", () {
                        _searchCountry(6);
                      }),
                      _button("Country by capital city", " Example: \"Delhi\"",
                          () {
                        _searchCountry(7);
                      }),
                      _button("Country by calling code", " Example: \"91\"",
                          () {
                        _searchCountry(8);
                      }),
                      _button("Country by continent", " Example: \"Asia\"", () {
                        _searchCountry(9);
                      }),
                      _button("Country by regional bloc", " Example: \"ASEAN\"",
                          () {
                        _searchCountry(10);
                      }),
                    ],
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _button(String title, String example, Function onPressed) {
    return Container(
      height: 60,
      width: MediaQuery.of(context).size.width * .5,
      margin: EdgeInsets.symmetric(vertical: 4, horizontal: 8),
      child: MaterialButton(
          color: Colors.blue[400],
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(10))),
          onPressed: onPressed,
          child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  title,
                  style: Theme.of(context).typography.dense.bodyText1,
                ),
                example.isEmpty
                    ? SizedBox()
                    : Text(
                        example,
                        style: Theme.of(context).typography.dense.bodyText1,
                      ),
              ])
          // visualDensity: VisualDensity.standard,
          ),
    );
  }

  Widget _countryData(Country model) {
    return Container(
      // padding: EdgeInsets.all(8),
      margin: EdgeInsets.symmetric(vertical: 8, horizontal: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
        boxShadow: <BoxShadow>[
          BoxShadow(
            blurRadius: 5,
            color: Color(0xfff6f6f6),
            offset: Offset(5, 5),
          )
        ],
      ),
      child: Theme(
        data: ThemeData(dividerColor: Colors.transparent),
        child: ExpansionTile(
          title: _title(model.name),
          children: <Widget>[
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Divider(color: Colors.grey.shade300, height: 1),
                Padding(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      _rowData("Capital", model.capital),
                      _rowData("Region", model.region),
                      _rowData("Alpha2 Code", model.alpha2Code),
                      _rowData("Alpha3 Code", model.alpha3Code),
                      _rowData("Area", model.area.toString()),
                      _showListData("Domain",
                          model.topLevelDomain.map((e) => e).toList()),
                      _rowData("Demonym", model.demonym),
                      _rowData("Timezone", model.timezones?.first),
                      _rowData("Calling code", model.callingCodes?.first),
                      _rowData("Numeric Code", model.numericCode),
                      _rowData("CIOS", model.cioc),
                      _showListData("Currency Name",
                          model.currencies?.map((x) => x?.name)?.toList()),
                      _showListData("Currency code",
                          model.currencies?.map((x) => x?.code)?.toList()),
                      _showListData("Currency Symbol",
                          model.currencies?.map((x) => x?.symbol)?.toList()),
                      _showListData("Lat Long",
                          model.latlng.map((e) => e.toString()).toList()),
                      _showListData("Language",
                          model.languages.map((e) => e.name).toList()),
                      _showListData("Lang Naiive Name",
                          model.languages.map((e) => e.nativeName).toList()),
                      _showListData("Lang iso6391 Code",
                          model.languages.map((e) => e.iso6391).toList()),
                      _showListData("Lang iso6392 Code",
                          model.languages.map((e) => e.iso6392).toList()),
                      _showListData("Regional Blocs",
                          model.regionalBlocs.map((e) => e.name).toList()),
                      _showListData("Regional Blocs Aacronym",
                          model.regionalBlocs.map((e) => e.acronym).toList()),
                      _showListData("Borders", model.borders),
                      _showListData("Alt Spellings", model.altSpellings),
                      _showListData(
                          "Name Translations",
                          model.translations
                              .toJson()
                              .cast<String, String>()
                              .values
                              .toList()),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _title(String text) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 4),
      child: Text(text),
    );
  }

  Widget _rowData(String text, String value) {
    return value == 'null' || value == null
        ? SizedBox()
        : materialWidget(
            Row(
              children: <Widget>[
                Expanded(
                  flex: 3,
                  child: Text(
                    text,
                    style: Theme.of(context)
                        .typography
                        .dense
                        .button
                        .copyWith(color: Colors.black),
                  ),
                ),
                Text(":  "),
                Expanded(
                  flex: 4,
                  child: Text(
                    value,
                    style: Theme.of(context)
                        .typography
                        .black
                        .bodyText1
                        .copyWith(color: Colors.black.withOpacity(.7)),
                  ),
                )
              ],
            ),
          );
  }

  Widget _showListData(String title, List<String> list) {
    if (list == null || list.isEmpty) {
      return SizedBox.shrink();
    }
    List<Widget> children = [
      Expanded(
        flex: 3,
        child: Text(
          title,
          style: Theme.of(context)
              .typography
              .dense
              .button
              .copyWith(color: Colors.black),
        ),
      )
    ];
    children.add(Text(":  "));
    children.add(
      Expanded(
        flex: 4,
        child: Container(
          child: Wrap(
            children: list.map((e) {
              if (list.last != e) {
                e = "$e, ";
              }

              return Padding(
                padding: EdgeInsets.only(right: 8),
                child: Text(e ?? ""),
              );
            }).toList(),
          ),
        ),
      ),
    );
    return materialWidget(
      Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: children),
    );
  }

  Widget materialWidget(Widget child) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 8),
      child: Material(
        shape: OutlineInputBorder(
            borderSide: BorderSide(color: Colors.black.withOpacity(.08)),
            borderRadius: BorderRadius.all(Radius.circular(2))),
        child: Container(
            margin: EdgeInsets.symmetric(vertical: 8),
            padding: const EdgeInsets.symmetric(horizontal: 8),
            child: child),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      backgroundColor: Color(0xfff1f1f1),
      floatingActionButton: FloatingActionButton(
        onPressed: openSearchCountriesButton,
        child: Icon(Icons.search),
      ),
      body: Container(
        alignment: Alignment.center,
        child: isLoading
            ? Center(child: CircularProgressIndicator())
            : _countryList != null && _countryList.isNotEmpty
                ? ListView.builder(
                    itemCount: _countryList.length,
                    itemBuilder: (context, index) {
                      if (_countryList[index] != null) {
                        return _countryData(_countryList[index]);
                      } else {
                        return SizedBox.shrink();
                      }
                    })
                : Text(
                    "Click search buton to select option",
                    style: Theme.of(context)
                        .typography
                        .dense
                        .bodyText1
                        .copyWith(color: Colors.black),
                  ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  country_provider: ^1.0.1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:country_provider/country_provider.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
60
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
80
Learn more about scoring.

We analyzed this package on Jul 11, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.14
  • Flutter: 1.17.5

Analysis suggestions

Package not compatible with SDK dart

Because:

  • country_provider that is a package requiring null.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.7.0 <3.0.0
flutter 0.0.0
http ^0.12.1 0.12.1
Transitive dependencies
charcode 1.1.3
collection 1.14.12 1.14.13
http_parser 3.1.4
meta 1.1.8 1.2.2
path 1.7.0
pedantic 1.9.0 1.9.2
sky_engine 0.0.99
source_span 1.7.0
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6 1.2.0
vector_math 2.0.8 2.1.0-nullsafety
Dev dependencies
flutter_test