forked from vandadnp/flutter-tips-and-tricks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptional-functions-in-dart.dart
More file actions
33 lines (29 loc) · 933 Bytes
/
optional-functions-in-dart.dart
File metadata and controls
33 lines (29 loc) · 933 Bytes
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
// Free Flutter Course 💙 https://linktr.ee/vandadnp
// Want to support my work 🤝? https://buymeacoffee.com/vandad
typedef AppBlocRandomUrlPicker = String Function(Iterable<String> allUrls);
extension RandomElement<T> on Iterable<T> {
T getRandomElement() => elementAt(
math.Random().nextInt(length),
);
}
class AppBloc extends Bloc<AppEvent, AppState> {
String _pickRandomUrl(Iterable<String> allUrls) => allUrls.getRandomElement();
AppBloc({
required Iterable<String> urls,
AppBlocRandomUrlPicker? urlPicker,
}) : super(const AppState.empty()) {
on<LoadNextUrlEvent>(
(event, emit) {
emit(
const AppState(
isLoading: true,
data: null,
),
);
// pick a random URL to load
final url = (urlPicker ?? _pickRandomUrl)(urls);
HttpClient().getUrl(Uri.parse(url)); // continue here...
},
);
}
}