How do i get Device Country code and currency in my Flutter application

Last updated Mar 02, 2022

While develop applications it may require to get current country information of the device location, like name of the country, country code, country currency etc. We will use to get current country code we implement Geo-location feature then fetch country information form the current latlang values. There is an other way to fetch current country code. In this flutter example we will see how to fetch current country code of the device.

To fetch current country code we will call a network api ip-api.com, it will returns information like country name, country code, currency...

 

Let get started

Step 1: Create Flutter application

Step 2: Add required dependencies in pubspec.yaml file

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3

Step 3: Create a class Network to handle api calls

To call api we will use below code

  Future apiRequest(Map jsonMap) async {
    HttpClient httpClient = new HttpClient();
    HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
    request.headers.set('content-type', 'application/x-www-form-urlencoded');
    request.add(utf8.encode(json.encode(jsonMap)));
    HttpClientResponse response = await request.close();
    // todo - you should check the response.statusCode
    String reply = await response.transform(utf8.decoder).join();
    httpClient.close();
    return reply;
  }

 

Step 4: Now call method form main dart file on button click

  Future getCountry() async{
    Network n = new Network("http://ip-api.com/json");
    String locationSTR = (await n.getData());
    var  locationx = jsonDecode(locationSTR);
    print("locationx ${locationx}");
    return locationx;
  }

 

It will returns data in key values pair, we can read data like below

var country = ${countrydata['country']}\nCountry Code = ${countrydata['countryCode']}\nTimezone = ${countrydata['timezone']

 

Complete example code to get current device country code and currency code

main dart file

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_country_code/api_call.dart';

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

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home:  MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State {
  String countryDetails="";

  @override
  Widget build(BuildContext context) {

    return Scaffold(body: Container(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () async{
                Mapcountrydata=await getCountry();
                setState(() {
                  countryDetails="Country = ${countrydata['country']}\nCountry Code = ${countrydata['countryCode']}\nTimezone = ${countrydata['timezone']}\n";

                });


              }, child: Text("Get My Country Code"),
            ),
            Text(countryDetails,style: TextStyle(fontSize: 20),)
          ],
        ),
      ),
    ),);
  }

  Future getCountry() async{
    Network n = new Network("http://ip-api.com/json");
    String locationSTR = (await n.getData());
    var  locationx = jsonDecode(locationSTR);
    print("locationx ${locationx}");
    return locationx;
  }
}

 

 

 

Network. dart file


import 'dart:convert';
import 'dart:io';

import 'package:http/http.dart' as http;

class Network {
  final String url;

  Network(this.url);

  Future apiRequest(Map jsonMap) async {
    HttpClient httpClient = new HttpClient();
    HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
    request.headers.set('content-type', 'application/x-www-form-urlencoded');
    request.add(utf8.encode(json.encode(jsonMap)));
    HttpClientResponse response = await request.close();
    // todo - you should check the response.statusCode
    String reply = await response.transform(utf8.decoder).join();
    httpClient.close();
    return reply;
  }

  Future sendData(Map data) async {
    http.Response response = await http.post(Uri.parse(url),
        headers: {'Content-Type': 'application/json; charset=UTF-8'},
        body: jsonEncode(data));
    if (response.statusCode == 200)
      return (response.body);
    else
      return 'No Data';
  }

  Future getData() async {
    http.Response response = await http.post(Uri.parse(url),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'});
    if (response.statusCode == 200)
      return (response.body);
    else
      return 'No Data';
  }
}

 

Conclusion: In this flutter example we covered how to get current country code and currency

 

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1744 Views