forked from What-the-Flutter/Isolate-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloading_compute.dart
48 lines (42 loc) · 1.17 KB
/
loading_compute.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
import 'dart:async';
import 'dart:convert';
import 'package:compute/compute.dart';
import 'package:http/http.dart' as http;
void main() async {
await loadDataFromCompute();
}
Future<void> loadDataFromCompute() async {
List<Map<String, dynamic>> result = [];
for (int i = 0; i < 10; i++) {
result.add(await compute(fetchData, 5));
}
// alternative way
result = await compute((int count) async {
List<Map<String, dynamic>> list = [];
for (int i = 0; i < 10; i++) {
list.add(await fetchData(count));
}
return list;
}, 5,);
}
Future<Map<String, dynamic>> fetchData(int requestCount) async {
final url = Uri.parse('https://api.example.com/data');
List<Future<http.Response>> futures = [];
for (int j = 0; j < requestCount; j++) {
futures.add(http.get(url));
}
try {
final responses = await Future.wait(futures);
for (var response in responses) {
if (response.statusCode == 200) {
final jsonData = jsonDecode(response.body);
return jsonData;
} else {
print('Request failed with status: ${response.statusCode}');
}
}
} catch (e) {
print('An error occurred: $e');
}
return {};
}