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】Dioを使ってHTTPリクエスト(GET)

Posted at

使用パッケージ

叩くAPIは openweathermap を使わせてもらう。

使い方

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

dependencies:
  json_annotation: ^4.8.1
  dio: ^5.1.2

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 dio = Dio();
    final response = await dio.get(url);
    final cityWeatherMap = json.decode(response.toString());

    final city = City.fromJson(cityWeatherMap);

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

(http と比較して)
URLの文字列をそのまま投げられる。
レスポンスはオブジェクトなので toString() してデコードする。

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?