Device Country in Flutter

Aleem picture Aleem · Sep 17, 2019 · Viewed 9.7k times · Source

I am trying to get country of device (Android) in Flutter. I used this tutorial, but I think it is the wrong approach for my problem.

Locale myLocale = Localizations.localeOf(context);
print(myLocale.languageCode.toString() + ' ' + myLocale.countryCode.toString());

Based on this, I have couple of questions/issues:

  • I am always getting en US even though I have set device language to Urdu - Pakistan. So what am I missing?
  • I want to display certain app items based on the country the device is in, not based on language as people living in Pakistan with language set to English (US) will get items actually intended for USA based users. So, should I use geoLocation and get longitude and latitude and decide based on that data? Or is there any other simpler approach just to get country of user?

Thanking in anticipation.

Answer

frankenstein picture frankenstein · Jun 16, 2020

Add this 2 library in pubspec.yaml

geolocator: ^5.1.1
geocoder: ^0.2.1

Then Add permission for Location access. Check here

At last call this method where you want.

Future<String> getCountryName() async {
    Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    debugPrint('location: ${position.latitude}');
    final coordinates = new Coordinates(position.latitude, position.longitude);
    var addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates);
    var first = addresses.first;
    return first.countryName; // this will return country name
}