How to get current country of device without asking for location permission? Flutter
Asked Answered
J

2

13

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?

Judicious answered 6/9, 2020 at 19:46 Comment(0)
E
38

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 
   }
Eleusis answered 6/9, 2020 at 19:57 Comment(4)
Worth.. : ) but these services are paid one for bulk usage.Nerva
Sadly that's not free api .it has limitGreasepaint
Thanks, but these types of websites don't work for users with VPNs, for example, all of our Iranian users are using VPNs constantly.Numerator
The free endpoint is limited to 45 requests / minuteOven
A
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.

Agrostology answered 1/10, 2020 at 9:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.