dart语法速览

dart语法速览

类与构造


class Ui {
  String view;

  Ui();

  Ui.buildView(this.view);
}

abstract class Engine {
  String draw();
}

class Point extends Ui implements Engine {
  int x;
  int y;

  Point(this.x, this.y, String view) : super.buildView(view);

  Point.fromJson(Map<String, int> json)
      : x = json['x'],
        y = json['y'] {
    this.view = '($x, $y)';
  }

  num get area => x * y;

  set area(int area) => x = (area / 2) as int;

  @override
  String draw() {
    return "draw rect($x,$y)";
  }

  Point operator +(Point p) {
    return Point(x + p.x, y + p.y, view + p.view);
  }
}

泛型

T drawLine<T extends Engine>(T t) {
  var shape = t.draw();
  print(shape);
  return t;
}

Factory与私有

class Logger {
  final String name;
  bool mute = false;

  // _cache is library-private, thanks to
  // the _ in front of its name.
  static final Map<String, Logger> _cache = <String, Logger>{};
  //工厂构造函数
  factory Logger(String name) {
    if (_cache.containsKey(name)) {
      return _cache[name];
    } else {
      final logger = Logger._internal(name);
      _cache[name] = logger;
      return logger;
    }
  }

  Logger._internal(this.name);

  void log(String msg) {
    if (!mute) print(msg);
  }
}

生成器

Iterable<int> naturalsDownFrom(int n) sync* {
  if (n > 0) {
    yield n;
    yield* naturalsDownFrom(n - 1);
  }
}

类型别名

typedef Compare = int Function(Object a, Object b);

class SortedCollection {
  Compare compare;

  SortedCollection(this.compare);
}

// Initial, broken implementation.
int sort(Object a, Object b) => 0;

void main() {
  SortedCollection coll = SortedCollection(sort);
  assert(coll.compare is Function);
  assert(coll.compare is Compare);
}
typedef Compare<T> = int Function(T a, T b);

int sort(int a, int b) => a - b;

void main() {
  assert(sort is Compare<int>); // True!
}

异步

Future<String> lookUpVersion() async {
  return '1.0.0';
}

void main() async {
  var version = await lookUpVersion();
  print(version);
  lookUpVersion().then((item) {
    print(item is String);
  });
  Future(lookUpVersion)
      .then((str) {
        print(str);
        return str.toUpperCase();
      })
      .then((up) => up.length)
      .then((size) {
        print(size);
      })
      .whenComplete(() {
        print("finish");
      });
}

猜你喜欢

转载自blog.csdn.net/weixin_33755649/article/details/87225916
今日推荐