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

2,834

Solution 1

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 
   }

Solution 2

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.

Share:
2,834
user6288393
Author by

user6288393

Updated on December 24, 2022

Comments

  • user6288393
    user6288393 over 1 year

    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?