今回やりたかったこと
今開発しているアプリで天気情報の取得が必要だったのでAPIを探したところこちらがヒットした。
使用方法
1.pubspec.yaml
にhttpパッケージを追加する
dependencies:
flutter:
sdk: flutter
http: ^0.13.3
flutter pub get
を忘れずに!
2.APIにリクエストを送れるようにする
class WeatherService {
static const String apiKey = //取得したAPIキー ;
static const String apiUrl =
//天気を取得した一点のURL;
Future<Map<String, dynamic>> fetchWeather() async {
try {
final response = await http.get(Uri.parse(apiUrl));
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
throw Exception('天気情報の取得に失敗しました');
}
} catch (e) {
throw Exception('エラー: $e');
}
}
}
URLは、天気情報が欲しい地名で登録もできるけど、
上手く取得できないときは、緯度経度を指定して特定の場所を指定することもできるよ!
'https://api.openweathermap.org/data/2.5/weather?lat=緯度&lon=経度&appid=$apiKey&units=metric';
3.あとは情報を使うだけで私は今回Riverpod
を使いました!
// WeatherService インスタンスを作成
final weatherServiceProvider = Provider((ref) => WeatherService());
// 天気情報を非同期で取得する FutureProvider(Weather 型に変更)
final weatherProvider = FutureProvider<Weather>((ref) async {
final weatherService = ref.read(weatherServiceProvider);
final weatherData = await weatherService.fetchWeather();
return Weather.fromJson(weatherData);
});
補足
実は、OpenWetherMapAPIには天気アイコンが用意されているよ!
https://openweathermap.org/weather-conditions
昼と夜で分けてくれているので自分でアイコン指定したい場合は、こんな感じでやってみてもいいと思いました。
switch (weatherIconCode) {
case '01d': // 晴れ(昼)
case '01n': // 晴れ(夜)
return const Icon(
Icons.wb_sunny,
color: Color.fromARGB(255, 255, 157, 59),
);
case '02d': // 少し曇り(昼)
case '02n': // 少し曇り(夜)
return const Icon(Icons.cloud, color: Colors.grey);
注意点
無料枠は1日1000回の呼び出しになってます。
いろんなプランがあるので確認してみてください!
最後に
初投稿となりますが、閲覧いただきありがとうございました。