Skip to content

Instantly share code, notes, and snippets.

@AndresR173
Created November 5, 2020 13:59
Show Gist options
  • Save AndresR173/78d8c5f41fd5b2e34c5891c9752d16c4 to your computer and use it in GitHub Desktop.
Save AndresR173/78d8c5f41fd5b2e34c5891c9752d16c4 to your computer and use it in GitHub Desktop.
Generics, Futures, Extensions in Dart
void main() async {
//Dynamic List
var list = [];
list.add(1);
list.add('2');
print(list);
// Callbacks
void downloadImage(Function(int) callback) {
int progress = 0;
while (progress < 100) {
progress++;
callback(progress);
}
}
downloadImage((progress) => print(progress));
downloadImage(print);
downloadImage((progress) {
final text = '$progress%';
print(text);
});
// Generics
ImageSize size = stringToEnum("medium", ImageSize.values);
print(size.resolution);
PostType post = stringToEnum("video", PostType.values);
print(post);
print(ImageSizeExtension.getMaxResolution());
// Null Safety
int a = 1;
int b = null;
print(a + (b ?? 0));
print(b?.abs());
b ??= 0;
print(a + b);
// Async Functions
countSeconds(5);
await printOrderMessage();
}
T stringToEnum<T>(String str, Iterable<T> values) {
return values.firstWhere(
(value) => value.toString().split('.')[1] == str,
orElse: () => null,
);
}
enum ImageSize { small, medium, large }
enum PostType { picture, video, reel }
// Extension
extension ImageSizeExtension on ImageSize {
int get resolution {
switch (this) {
case ImageSize.small:
return 300;
case ImageSize.medium:
return 700;
case ImageSize.large:
return 1024;
}
}
static int getMaxResolution() => ImageSize.large.resolution;
}
void countSeconds(int s) {
for (var i = 1; i <= s; i++) {
Future.delayed(Duration(seconds: i), () => print(i));
}
}
Future<void> printOrderMessage() async {
print('Awaiting user order...');
var order = await fetchUserOrder();
print('Your order is: $order');
}
Future<String> fetchUserOrder() {
return Future.delayed(Duration(seconds: 4), () => 'Large Latte');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment