0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Flutter】HTTPリクエスト(GET)

Last updated at Posted at 2023-05-21

使用パッケージ

を使用して、HTTPリクエストしてみる。
なおAPIは openweathermap を使わせてもらう。

使い方

pubspec.yaml にパッケージを追加

dependencies:
  json_annotation: ^4.8.1
  http: ^0.13.6

dev_dependencies:
  build_runner: ^2.4.4
  json_serializable: ^6.7.0

APIの取得結果であるJSON文字列を、クラスに詰め替えるのに、
json_serializable を使用したので、ついでにそのパッケージも追加。

使ってみる

    final urlPath = 'https://api.openweathermap.org/data/2.5/weather';
    // 東京タワーの緯度経度
    final lat = '35.6579781';
    final lon = '139.7433048';
    final appid = 'xxxxxxxxxx';
    final units = 'metric';
    final lang = 'ja';
    final url = '${urlPath}?lat=${lat}&lon=${lon}&appid=${appid}&units=${units}&lang=${lang}';

    final response = await http.get(Uri.parse(url));
    final cityWeatherMap = json.decode(response.body);

    final city = City.fromJson(cityWeatherMap);

    // とりあえず場所と天気だけ表示
    print('CityWeathre: ${city.id}, ${city.name}, ${city.weather?[0].description}');

URLの文字列をUri形式に変換してGETする。
レスポンスの body がJSON文字列なので、そのままデコードすればOK。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?