Created
December 27, 2021 13:16
-
-
Save tetujin/ab18c4a447dd2e950cb53a3d453cea4f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// ① APIの利用に必要なライブラリをインポートする | |
import 'package:http/http.dart' as http; | |
import 'dart:convert' as convert; | |
void main() async { | |
// ② APIにアクセスする | |
var url = Uri.parse( | |
'https://mocha-api.t.u-tokyo.ac.jp/resource/channel/utokyo_all/congestion'); | |
var response = await http.get(url); | |
// ③ status code を確認する。 | |
// status codeの種類は、API Documentに記述されている | |
print(response.statusCode); | |
// ④ status codeに応じて処理を分岐する(if文の活用) | |
if (response.statusCode == 200) { // 通信が成功した場合の処理 | |
// APIからへの返信の中身を確認 | |
print(response.body); | |
// ⑤ JSON形式の"文字列"を`convert`ライブラリを使って、辞書型に変換 | |
var jsonObj = convert.jsonDecode(response.body); | |
print(jsonObj); | |
// ⑥ 辞書型の中から、`congestions`(混雑状況)に関する要素(配列)を取得 | |
// データ形式の詳細はAPI Documentを確認する | |
List<dynamic> congestions = jsonObj['congestions']; | |
print(congestions); | |
// ⑦ for文を用いて、配列の要素に対して処理を加える | |
for (Map<String, dynamic> congestion in congestions) { | |
var headcount = congestion['headcount']; // 滞在者の人数 | |
Map<String, dynamic> space = congestion['space']; | |
var name = space['nameJa']; // スペースの名前 | |
var capacity = space['capacity']; // スペースの容量 | |
var outletCount = space['outletCount']; // コンセントの数 | |
// ⑧ 取得した情報を可視化する | |
print( | |
"$name:($headcount/$capacity)[$outletCount]"); | |
} | |
} else if (response.statusCode == 500) { // エラーハンドリング | |
print("server-side error"); | |
} else { // エラーハンドリング | |
print("unkwon error"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment