Created
May 26, 2022 12:31
-
-
Save philippkeller/55407cb6249d5a0f7bfee7d3d16acf0e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:http/http.dart' as http; | |
import 'dart:convert'; | |
const apiKey = 'my-secret-api-key'; | |
class Weather { | |
final int temp; | |
final int condition; | |
final String city; | |
Weather._(this.temp, this.condition, this.city); | |
String getWeatherIcon() { | |
if (condition < 300) { | |
return '🌩'; | |
} else if (condition < 400) { | |
return '🌧'; | |
} else if (condition < 600) { | |
return '☔️'; | |
} else if (condition < 700) { | |
return '☃️'; | |
} else if (condition < 800) { | |
return '🌫'; | |
} else if (condition == 800) { | |
return '☀️'; | |
} else if (condition <= 804) { | |
return '☁️'; | |
} else { | |
return '🤷'; | |
} | |
} | |
String getMessage() { | |
if (temp > 25) { | |
return 'It\'s 🍦 time'; | |
} else if (temp > 20) { | |
return 'Time for shorts and 👕'; | |
} else if (temp < 10) { | |
return 'You\'ll need 🧣 and 🧤'; | |
} else { | |
return 'Bring a 🧥 just in case'; | |
} | |
} | |
@override | |
String toString() { | |
return 'temp: $temp, condition: $condition, city: $city'; | |
} | |
static Future<Weather> create( | |
{required double lat, required double lon}) async { | |
Uri url = Uri.https('api.openweathermap.org', 'data/2.5/weather', { | |
'lat': lat.toString(), | |
'lon': lon.toString(), | |
'appid': apiKey, | |
'units': 'metric' | |
}); | |
http.Response resp = await http.get(url); | |
if (resp.statusCode != 200) { | |
throw 'got statusCode $resp.statusCode'; | |
} | |
final data = jsonDecode(resp.body); | |
final double temp = data['main']['temp']; | |
final int condition = data['weather'][0]['id']; | |
final String city = data['name']; | |
return Weather._(temp.toInt(), condition, city); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment