Calling the Weather API

Using the Weather API

This is a small Flutter App that explains the very basics of calling APIs. In this app we call the Weather API at (go and look up the site here)

Register yourself on the site and get an appid for yourself
Here is a list of the available APIs

This link will give the currentweather of Varanasi (my hometown)

The data is accessed via the http dart package which is hosted at

The data is downloaded in JSON. To convert into a Dart Map we use the dart convert package



The relevant code is:






Future < bool > getWeather(String
cityname) async {
String
apikey = "4a1f8a61b74546825af1e0be106e797b";
final
url = Uri.https("api.openweathermap.org", "/data/2.5/forecast",
{'q': cityname, 'appid': apikey, 'units': 'metric'});

try {
final response = await http.get(url);

print(response);
print(response.statusCode);
final jsonResponse = convert.jsonDecode(response.body);
print(jsonResponse);
print(jsonResponse.runtimeType);
Map < String, dynamic > map = jsonResponse;
print(map.keys);
for (String key in map.keys) {
dynamic value = map[key];
print(key + " = " + value.toString());
}
print("icon" + map["list"][0]["weather"][0]["icon"].toString());
currenticon = map["list"][0]["weather"][0]["icon"].toString();

currentcitytemp = map["list"][0]["main"]["temp"].toString();
currentmaxtemp = map["list"][0]["main"]["temp_max"].toString();
currentmintemp = map["list"][0]["main"]["temp_min"].toString();
description = map["list"][0]["weather"][0]["description"].toString();
weatherfound = true;

return true;
} catch(ex)
{
print(ex);
weatherfound = false;
currentcitytemp = "-";
currentmaxtemp = "-";
currentmintemp = "-";
description = "-";
return false;
}
}





Type a city name and press the Get Weather button.










 

Post a Comment

0 Comments

Me