forked from Mr-Sunglasses/flutter-tips-and-tricks
-
Notifications
You must be signed in to change notification settings - Fork 1
/
dart-progress-for-futuret.dart
64 lines (55 loc) · 1.65 KB
/
dart-progress-for-futuret.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
// Want to support my work 🤝? https://buymeacoffee.com/vandad
import 'dart:io' show stdout;
import 'dart:async' show Future, Stream;
const loadingSequence = ['⢿', '⣻', '⣽', '⣾', '⣷', '⣯', '⣟', '⡿'];
const escape = '\x1B[38;5;';
const color = '${escape}1m';
const textColor = '${escape}6m';
String progress({required int value, required String text}) {
final progress = '$color${loadingSequence[value % loadingSequence.length]}';
final coloredText = '$textColor$text';
return '$progress\t$coloredText';
}
Future<T> performWithProgress<T>({
required Future<T> task,
required String progressText,
}) {
final stream = Stream<String>.periodic(
Duration(milliseconds: 100),
(value) => progress(
value: value,
text: progressText,
),
);
final subscription = stream.listen(
(event) {
stdout.write('\r $event');
},
);
task.whenComplete(() {
stdout.write('\r ✅\t$progressText');
stdout.write('\n');
subscription.cancel();
});
return task;
}
final task1 = Future.delayed(Duration(seconds: 1), () => 'Result 1');
final task2 = Future.delayed(Duration(seconds: 2), () => 'Result 2');
final task3 = Future.delayed(Duration(seconds: 3), () => 'Result 3');
void main(List<String> args) async {
var result = await performWithProgress(
task: task1,
progressText: 'Loading task 1',
);
print('\tTask 1 result: $result');
result = await performWithProgress(
task: task2,
progressText: 'Loading task 2',
);
print('\tTask 2 result: $result');
result = await performWithProgress(
task: task3,
progressText: 'Loading task 3',
);
print('\tTask 3 result: $result');
}