Dart学习笔记(二)

免责声明:本文档基本是官网文档的摘抄和简单翻译,几乎没有任何原创。
本文是我本人对Dart学习所做的笔记,目的是记录和整理。
Dart里的一些显著不同于其他编程语言的语法整理。
Dart具有多种编程范式,这点和C++相同,不强制面向对象。然而在各种语法上更接近Java和C#,除了没有public、protected、private之类的修饰关键字。
下面的东西为我个人笔记,无意做教程,所以写的比较乱。不过反正也应该没什么人看。

1.构造函数:初始化成员变量的语法糖

class Point {
  num x, y;

  // Syntactic sugar for setting x and y
  // before the constructor body runs.
  Point(this.x, this.y);
}

2.Named constructors(命名构造函数)

class Point {
  num x, y;
  Point(this.x, this.y);
  // Named constructor
  Point.origin() {
    x = 0;
    y = 0;
  }
}

3.调用父类非默认的构造函数(默认构造函数应该就是无参构造函数)

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');
  }
}

或者只初始化父类构造函数就结束,无需写{},直接加分号结束

class Employee extends Person {
  Employee() : super.fromJson(getDefaultData());
  // ···
}

4.初始化列表

class Point {
  final num x;
  final num y;
  final num distanceFromOrigin;

  Point(x, y)
      : x = x,
        y = y,
        distanceFromOrigin = sqrt(x * x + y * y);

  // Initializer list sets instance variables before
  // the constructor body runs.
  Point.fromJson(Map json)
      : x = json['x'],
      y = json['y'] {
    print('In Point.fromJson(): ($x, $y)');
  }
}
  1. getter ,setter
class Rectangle {
  num left, top, width, height;

  Rectangle(this.left, this.top, this.width, this.height);

  // Define two calculated properties: right and bottom.
  num get right => left + width;
  set right(num value) => left = value - width;
  num get bottom => top + height;
  set bottom(num value) => top = value - height;
}

6.隐式接口
每个类隐式地声明了一个接口,此接口的成员包括这个类所有的实例成员及它所实现接口的函数。
如果类A想要实现类B的API,并且不继承类B的任何实现方式,只需要通过implements关键字来实现B即可,而不是extends。
这说明Dart不使用interface关键字来声明接口,而每个类都是接口,只要被其他类implements。

// A person. The implicit interface contains greet().
class Person {
  // In the interface, but visible only in this library.
  final _name;
  // Not in the interface, since this is a constructor.
  Person(this._name);
  // In the interface.
  String greet(String who) => 'Hello, $who. I am $_name.';
}
// An implementation of the Person interface.
class Impostor implements Person {
  get _name => '';
  String greet(String who) => 'Hi $who. Do you know who I am?';
}

7.运算符重载,基本和C++相同

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);

  // Operator == and hashCode not shown. For details, see note below.
  // ···
}

8.继承,枚举,泛型基本和Java相同
区别在于dart的泛型有简写语法糖

var names = ['Seth', 'Kathy', 'Lars'];
var uniqueNames = {'Seth', 'Kathy', 'Lars'};
var pages = {
  'index.html': 'Homepage',
  'robots.txt': 'Hints for web robots',
  'humans.txt': 'We are people, not machines'
};

9.引入第三方库
可以使用路径引入本地库。
dart开头的库是dart自带的标准库。
package开头的库需要在 package manager 里,比如pub tool。

import 'dart:html';
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;

10.支持aynsc/await

Future checkVersion() async {
  var version = await lookUpVersion();
  // Do something with version
}
Future lookUpVersion() async => '1.0.0';

11.streams
可以直接使用for循环处理异步数据流

Future main() async {
  // ...
  await for (var request in requestServer) {
    handleRequest(request);
  }
  // ...
}
  1. Generators,生成器
    和python基本相同
    注意声明后边的sync*async*,导致了返回值的不同,分别返回了Iterable和Stream。
Iterable naturalsTo(int n) sync* {
  int k = 0;
  while (k < n) yield k++;
}
Stream asynchronousNaturalsTo(int n) async* {
  int k = 0;
  while (k < n) yield k++;
}

13.可调用的类(函子)(Callable classes)

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');
}
  1. Isolates 类似于线程
    dart:isolate library documentation.

15.typedef
与C++基本相同

typedef Compare = int Function(Object a, Object b);
class SortedCollection {
  Compare compare;
  SortedCollection(this.compare);
}
int sort(Object a, Object b) => 0;
void main() {
  SortedCollection coll = SortedCollection(sort);
}

16.元数据注解(Metadata)

library todo;

class Todo {
  final String who;
  final String what;

  const Todo(this.who, this.what);
}
//===========
import 'todo.dart';

@Todo('seth', 'make this do something')
void doSomething() {
  print('do something');
}

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