11

I just want to know the country where the device is at. Not the street, not the city, not the province. Just the country. I should be able to get that sort of coarse information without having to ask the user for location permissions, I see many apps and websites that somehow know in what country I currently am without asking me anything previously.

Is there any way to do this that works both on Android and iOS with Flutter?

(optional but highly appreciated) If an API is absolutely necessary to do this. Which one would be the cheapest?

user6288393
  • 187
  • 2
  • 11

2 Answers2

31

try this:

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

try {
      http.get('http://ip-api.com/json').then((value) {
      print(json.decode(value.body)['country'].toString());
      });
    } catch (err) {
      //handleError 
   }
farouk osama
  • 2,374
  • 2
  • 12
  • 30
5

You can use an IP geolocation service such as Ipregistry:

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

Future<String> lookupUserCountry() async {
  final response = await http.get('https://api.ipregistry.co?key=tryout');

  if (response.statusCode == 200) {
    return json.decode(response.body)['location']['country']['name'];
  } else {
    throw Exception('Failed to get user country from IP address');
  }
}

Note that on Android it requires the android.permission.INTERNET permission.

Laurent
  • 14,122
  • 13
  • 57
  • 89