0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

OpenWetherMap APIを使ってみた。

Posted at

今回やりたかったこと

今開発しているアプリで天気情報の取得が必要だったので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回の呼び出しになってます。
いろんなプランがあるので確認してみてください!

最後に

初投稿となりますが、閲覧いただきありがとうございました。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?