Dart笔记

类型和变量

  • 一切是对象 -> 默认值null
  • Object 优于 dynamic
  • finalconstvar
  • bool不支持其他类型强制转换
  • Symbol:#varName

函数

  • 函数也是对象
[Type] funName ([[Type] param1[, …]]) { 
  codeBlock;
}
  • 函数参数和返回类型可省略
  • => expr;可用于缩写{ return expr; }
  • 命名参数:
//define
funName({type1: param1, type2: param2}) {}
//call
funName(param1: val1, param2: val2);
  • 必选命名参数标记@required from meta.dart
  • 匿名参数,可选参数放在[]中,放在参数列表最后:
//define
funName(type1 param1, type2 param2, [type3 param3]) {}
//call
funName(val1, val2);
  • 匿名函数:
([[Type] param1[, …]]) { 
  codeBlock; 
};

操作符

  • ~/整除
  • is is! as
  • ..层叠操作符用来对一个对象进行连续多次操作
  • ?.允许操作对象为null

控制流

  • if else
  • for forEach() for in
  • while do-while
  • break continue
  • switch case
  • assert 测试环境抛AssertionError

异常

  • 方法不需声明自己可能抛出的异常
  • Error Exception以及任何类型的对象都可以被抛出
  • catch:
try {
  breedMoreLlamas();
} on OutOfLlamasException {
  // A specific exception
  buyMoreLlamas();
} on Exception catch (e) {
  // Anything else that is an exception
  print('Unknown exception: $e');
} catch (e) {
  // No specified type, handles all
  print('Something really unknown: $e');
} finally {
  // Always clean up, even if an exception is thrown.
  cleanLlamaStalls();
}

  • new是可选的
  • 抽象类abstract
  • 常量构造函数var p = const ImmutablePoint(2, 2);
  • 对象属性runtimeType用于发现对象类型,该属性类型是Type
  • 默认构造函数、命名构造函数,构造函数不继承
  • 继承:
class Person {
  String firstName;

  Person.fromJson(Map data) {
    print('in Person');
  }
}

class Employee extends Person {
  // Person does not have a default constructor;
  // you must call super.fromJson(data).
  Employee.fromJson(Map data) : super.fromJson(data) {
    print('in Employee');
  }
}
  • 初始化列表:
Point.fromJson(Map json)
    : x = json['x'],
      y = json['y'] {
  print('In Point.fromJson(): ($x, $y)');
}
  • 常量构造器:
class ImmutablePoint {
  static final ImmutablePoint origin =
      const ImmutablePoint(0, 0);

  final num x, y;
  const ImmutablePoint(this.x, this.y);
}
  • 工厂构造器:不能用this
class Logger {
  final String name;
  bool mute = false;

  // _cache is library-private, thanks to
  // the _ in front of its name.
  static final Map _cache =
      {};

  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);
  }
}
  • get set,也可以为抽象方法
  • 抽象方法必须定义在抽象类,不需加abstract
  • 所有class自动生成一个同名的接口类,可以被其他类implements
  • 部分运算符可重载,==hashCode get要一起重载
class Vector {
  final int x, y;

  Vector(this.x, this.y);

  Vector operator +(Vector v) => Vector(x + v.x, y + v.y);
  Vector operator -(Vector v) => Vector(x - v.x, y - v.y);
}
  • 重载noSuchMethod()可以避免NoSuchMethodError抛出
  • 枚举enum Identifier {...}index从0开始,Identifier.values常量可用于遍历枚举的元素
  • mixin用来声明一个mixin类型,扩展Object,其他类型使用with关键字实现mixin
  • 使用on限制可以使用mixin的类型
mixin MusicalPerformer on Musician {
}
  • static静态方法和成员
  • 限制泛型参数类型List

  • 内建库import 'dart:Xlib;'
  • 一般库import 'package:test/test.dart';
  • 特殊用法:
import 'package:lib1/lib1.dart';
import 'package:lib2/lib2.dart' as lib2;

// Import only foo.
import 'package:lib1/lib1.dart' show foo;

// Import all names EXCEPT foo.
import 'package:lib2/lib2.dart' hide foo;
  • 懒加载库
import 'package:greetings/hello.dart' deferred as hello;

Future greet() async {
  await hello.loadLibrary();
  hello.printGreeting();
}

异步

  • async await
await lookUpVersion();

Future checkVersion() async {
  var version = await lookUpVersion();
  // Do something with version
}
  • async方法不会阻塞,async方法返回Future
  • 使用try/catch/finally处理await里的错误和释放资源
  • await expression里的表达式通常是Future,如果不是也会被自动包装成Future
  • 使用asyncawait for处理流:
Future fun() async {
  // ...
  await for (var request in requestServer) {
    handleRequest(request);
  }
  // ...
}
  • 下面代码expression必须是Stream类型,使用break/return停止监听stream
await for (varOrType identifier in expression) {
  // Executes each time the stream emits a value.
}

生成器

  • 关键字sync*, yield
  • 同步生成器:Iterable
Iterable naturalsTo(int n) sync* {
  int k = 0;
  while (k < n) yield k++;
}
  • 异步生成器:Stream
Stream asynchronousNaturalsTo(int n) async* {
  int k = 0;
  while (k < n) yield k++;
}
  • 生成器如果是递归的,可以用yield*提升性能
Iterable naturalsDownFrom(int n) sync* {
  if (n > 0) {
    yield n;
    yield* naturalsDownFrom(n - 1);
  }
}

其他

  • 实现call()让一个类可以被调用
class WannabeFunction {
  call(String a, String b, String c) => '$a $b $c!';
}

main() {
  var wf = new WannabeFunction();
  var out = wf("Hi","there,","gang");
  print('$out');
}
  • dart:isolate:所有的dart代码运行在isolates中,不是线程,isolate内存对战独立,他的状态不能从外部访问
  • typedef只能用于方法
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);
}
  • metadata类似Java注解,可以自己定义

你可能感兴趣的:(Dart笔记)