Flutter get User's Country without Manual Permission

4.5k Views Asked by At

I have a Blog App where I write Bussiness Content for Global as well as some country-specific content. Like Special posts for India, Indonesia, etc.

That's why I need a way to find from which country the user is to provide specific content.

But, I don't want to use the GeoLocator Plugin because It will ask the User for location. I only want the user's country, not the specific location but the permission dialog didn't specify that which can make the user anxious about why this app needs Location Permission. That's why I want a way to get user's Country without an implicit permission dialog asking for their location.

I have tried the following ways but none of them gave the exact country name.

import 'dart:io' show Platform;

String localeName = Platform.localeName;

// this returns language device is using which mostly comes us en_US so this is of no use


Locale myLocale = Localizations.localeOf(context);
// This returned the US as the country despite the App being opened and used in India.
3

There are 3 best solutions below

3
On BEST ANSWER

Well, I finally found an easy and simple way to get users' country.

http://ip-api.com/json

This link returns the Users' location in a JSON format. So All one has to do now, is to make a Get request to the above link/API and decode the JSON to Map.

For that First Install HTTP Package:

Pubspec.yaml:

dependencies:
  http:

Code:

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

Response data = await http.get('http://ip-api.com/json');
Map data = jsonDecode(data.body);
String country = data['country'];

EDIT: As mentioned by good people,

Free Version Limit is 45 HTTP requests per second from an IP address.
2
On

Locale gives you the language that the device user has set. It does not necessarily indicate their country of birth. It definitely does not tell you their country of residence. It may be that in many cases the person IS in the country of the language code but that is not guaranteed. The only way to know where they are is by location.

Update Regarding your comment. If you mean where to get the country name based on the language code you get from the device locale, then have a look at this post. I haven't tried it myself but it seems promising. https://dev.to/thealphamerc/get-search-filter-countries-data-using-countryprovider-flutter-plugin-1epc

1
On

try this

import 'dart:io' show Platform;

String localeName = Platform.localeName

or try this

please use package devicelocale I have tested with real device, it works fine

code snippet

String locale = await Devicelocale.currentLocale;