forked from vandadnp/flutter-tips-and-tricks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
github-api-in-flutter.dart
106 lines (95 loc) · 2.88 KB
/
github-api-in-flutter.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Want to support my work 🤝? https://buymeacoffee.com/vandad
import 'dart:io' show HttpHeaders, HttpClient;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:convert' show utf8, json;
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
Future<Iterable<GithubUser>> getGithubFollowers(String accessToken) =>
HttpClient()
.getUrl(Uri.parse('https://api.github.com/user/followers'))
.then((req) {
req.headers
..set(HttpHeaders.authorizationHeader, 'Bearer $accessToken')
..set(HttpHeaders.contentTypeHeader, 'application/json');
return req.close();
})
.then((resp) => resp.transform(utf8.decoder).join())
.then((jsonStr) => json.decode(jsonStr) as List<dynamic>)
.then(
(jsonArray) => jsonArray.compactMap((element) {
if (element is Map<String, dynamic>) {
return element;
} else {
return null;
}
}),
)
.then(
(listOfMaps) => listOfMaps.map(
(map) => GithubUser.fromJson(map),
),
);
class GithubUser {
final String username;
final String avatarUrl;
GithubUser.fromJson(Map<String, dynamic> json)
: username = json['login'] as String,
avatarUrl = json['avatar_url'] as String;
}
extension CompactMap<T> on List<T> {
List<E> compactMap<E>(E? Function(T element) f) {
Iterable<E> imp(E? Function(T element) f) sync* {
for (final value in this) {
final mapped = f(value);
if (mapped != null) {
yield mapped;
}
}
}
return imp(f).toList();
}
}
const token = 'PUT_YOUR_TOKEN_HERE';
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('GitHub API in Flutter'),
),
body: FutureBuilder(
future: getGithubFollowers(token),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.done:
final users = (snapshot.data as Iterable<GithubUser>).toList();
return ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
final user = users[index];
return ListTile(
title: Text(user.username),
leading: CircularAvatar(url: user.avatarUrl),
);
},
);
default:
return const CircularProgressIndicator();
}
},
),
);
}
}
void main() {
runApp(
const MaterialApp(
home: HomePage(),
debugShowCheckedModeBanner: false,
),
);
}