https://api.github.com/events
我们把需要的信息找到,然后创建想要的对象
class GithubEvent {
late String id;
late String name;
late String avatar_url;
late String repo_name;
GithubEvent(Map<dynamic, dynamic> data) {
id = data["id"];
name = data['actor']['display_login'];
avatar_url = data['actor']['avatar_url'];
repo_name = data['repo']['name'];
}
@override
String toString() {
return 'GithubEvent{id: $id, name: $name, avatar_url: $avatar_url, repo_name: $repo_name}';
}
}
// 获取数据
getData() async {
final dio = Dio();
try {
final resp = await dio.get("<https://api.github.com/events>");
if (resp.statusCode == 200) {
setState(() {
_events.clear();
_events.addAll((resp.data as List<dynamic>)
.map((item) => GithubEvent(item))
.toList());
});
print("refresh $_events");
}
} catch (e) {
print("Error: $e");
}
}
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<GithubEvent> _events = [];
@override
void initState() {
super.initState();
getData();
}
// 展示数据的UI
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Github动态"), centerTitle: true),
body: Scrollbar(
// 上拉刷新的组件
child: RefreshIndicator(
onRefresh: () => getData(),
// 展示的组件
child: ListView.separated(
itemCount: _events.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_events[index].repo_name),
leading: Image.network(_events[index].avatar_url),
);
}, separatorBuilder: (BuildContext context, int index) => const Divider(),),
),
),
);
}
}
https://book.flutterchina.club/chapter2/flutter_widget_intro.html