Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code sample for 'Use Extension Methods in Dart' lesson on Egghead.io
import 'dart:async';
getDuration(int seconds) {
return Duration(seconds: seconds);
}
extension MyInt on int {
Duration get seconds => Duration(seconds: this);
DateTime monthsAgo() => DateTime.now().subtract(Duration(hours: 24 * 30 * this));
}
extension MyString on String {
bool isValidEmail() => RegExp('^[a-z]*@[a-z]*\.com', caseSensitive: false).hasMatch(this);
// final notallowed = true;
}
extension MyStreamController<T> on StreamController<T> {
void set latest(item) => this.add(item);
}
void main() {
print(getDuration(2));
Future.delayed(getDuration(2), () => print('2 seconds passed'));
print(2.seconds);
print(MyInt(2).seconds);
Future.delayed(2.seconds, () => print('2 seconds elapsed'));
print(2.monthsAgo());
print(MyInt(2).monthsAgo());
print('super@gmail.com'.isValidEmail());
print('notanemail'.isValidEmail());
StreamController<int> controller = StreamController<int>();
controller.stream.listen((value) => print('Got value $value'));
controller.latest = 5;
controller.latest = 10;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment