进阶专题

高级特性

生成器

generators.dart
Iterable naturalsTo(int n) sync* {
  var k = 0;
  while (k < n) yield k++;
}

Stream countDown(int from) async* {
  for (var i = from; i > 0; i--) {
    await Future.delayed(Duration(seconds: 1));
    yield i;
  }
}

扩展方法

extensions.dart
extension StringExtensions on String {
  bool get isEmail => RegExp(r'^[\w-\.]+@[\w-]+\.[\w-]{2,4}$').hasMatch(this);
  String capitalize() => isEmpty ? this : this[0].toUpperCase() + substring(1);
}
void main() {
  print('test@example.com'.isEmail); // true
  print('hello'.capitalize()); // Hello
}