Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 585
user6288393 Avatar asked Sep 06 '20 19:09

user6288393


People also ask

How do I change location permissions in flutter?

First, we require to check location permission is already granted or not. Now if location permission is not granted. Then we require to write a code to take location permission from a device. And based on result status.


2 Answers

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 
   }
like image 61
farouk osama Avatar answered Oct 20 '22 10:10

farouk osama


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.

like image 22
Laurent Avatar answered Oct 20 '22 10:10

Laurent