Skip to content

Instantly share code, notes, and snippets.

@graphicbeacon
Created November 8, 2019 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graphicbeacon/4d07d09d18a42c0633df59ae3b9b893f to your computer and use it in GitHub Desktop.
Save graphicbeacon/4d07d09d18a42c0633df59ae3b9b893f to your computer and use it in GitHub Desktop.
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