forked from vandadnp/flutter-tips-and-tricks
-
Notifications
You must be signed in to change notification settings - Fork 2
/
generic-url-retrieval-in-dart.dart
62 lines (56 loc) · 1.51 KB
/
generic-url-retrieval-in-dart.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
// Want to support my work 🤝? https://buymeacoffee.com/vandad
import 'dart:developer' as dev show log;
typedef StatusCodeResultBuilder<T> = Future<T> Function(
int statusCode,
HttpClientResponse response,
);
extension Get on Uri {
Future<T?> getBody<T>({
StatusCodeResultBuilder<T>? statusBuilder,
T Function(Object error)? onNetworkError,
}) async {
try {
final apiCall = await HttpClient().getUrl(this);
final response = await apiCall.close();
final builder = statusBuilder;
if (builder == null) {
final data = await response.transform(convert.utf8.decoder).join();
if (data is T) {
return data as T?;
} else {
return null;
}
} else {
final result = await builder(response.statusCode, response);
return result;
}
} catch (e) {
if (onNetworkError != null) {
return onNetworkError(e);
} else {
return null;
}
}
}
}
extension ToUri on String {
Uri toUri() => Uri.parse(this);
}
const url = 'https://bit.ly/3EKWcLa';
void testIt() async {
final json = await url.toUri().getBody<String>(
statusBuilder: (statusCode, response) async {
if (statusCode == 200) {
return await response.transform(convert.utf8.decoder).join();
} else {
return "{'error': 'Unexpected status code $statusCode'}";
}
},
onNetworkError: (error) {
return "{'error': 'Got network error'}";
},
);
if (json != null) {
dev.log(json);
}
}