-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_Country_From_IP
33 lines (32 loc) · 1.02 KB
/
get_Country_From_IP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Future<void> _getCountryFromIP() async {
try {
// Step 1: Get the public IP address
final ipResponse =
await http.get(Uri.parse('https://api.ipify.org?format=json'));
if (ipResponse.statusCode == 200) {
final Map<String, dynamic> ipData = json.decode(ipResponse.body);
final String ip = ipData['ip'];
// Step 2: Get the country information using the IP address
final response =
await http.get(Uri.parse('https://ipapi.com/ip_api.php?ip=$ip'));
if (response.statusCode == 200) {
final Map<String, dynamic> data = json.decode(response.body);
setState(() {
_country = data['country_name'] ?? 'Unknown';
});
} else {
setState(() {
_country = 'Failed to get country';
});
}
} else {
setState(() {
_country = 'Failed to get IP address';
});
}
} catch (e) {
setState(() {
_country = 'Error: $e';
});
}
}