Created
December 27, 2021 13:46
-
-
Save tetujin/629baae4307c8fa875df3b06b215b623 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
import 'package:flutter/material.dart'; | |
import 'package:http/http.dart' as http; | |
import 'dart:convert' as convert; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
theme: ThemeData(), | |
home: const MyHomePage(), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
const MyHomePage({ | |
Key? key, | |
}) : super(key: key); | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
// ① 混雑状況を表示するカードリストを準備 | |
List<Widget> cards = []; | |
void _refresh() async { | |
var url = Uri.parse( | |
'https://mocha-api.t.u-tokyo.ac.jp/resource/channel/utokyo_all/congestion'); | |
var response = await http.get(url); | |
if (response.statusCode == 200) { | |
var jsonObj = convert.jsonDecode(response.body); | |
List<dynamic> congestions = jsonObj['congestions']; | |
cards = []; // ③ 通信が成功したのでカードリストを初期化 | |
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']; // コンセントの数 | |
var info = "$name:($headcount/$capacity)[$outletCount]"; | |
// ④ カードをカードリストに追加し、変更箇所を画面に反映 | |
setState(() { | |
cards.add( | |
Card( | |
child: Container( | |
padding: const EdgeInsets.all(10), | |
child: Text(info), | |
), | |
), | |
); | |
}); | |
} | |
} else if (response.statusCode == 500) { | |
// エラーハンドリング | |
print("server-side error"); | |
} else { | |
// エラーハンドリング | |
print("unkwon error"); | |
} | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: const Text("混雑情報"), | |
), | |
body: Center( | |
// ⑤ ListView.builderを用いて、動的にリストを生成 | |
child: ListView.builder( | |
itemCount: cards.length, | |
itemBuilder: (BuildContext context, int index) { | |
return cards[index]; | |
}, | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
// ② refreshボタンが押されたタイミングで、APIにアクセスして | |
// 画面を更新するメソッドを呼ぶ | |
onPressed: _refresh, | |
tooltip: 'Increment', | |
child: const Icon(Icons.refresh), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment