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?
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.
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With