var gifts = {
// Key: Value
'first': 'partridge',
'second': 'turtledoves',
'fifth': 'golden rings'
};
函数
[]表示参数可选
{}命名参数
=使用默认值,必须是编译时常量,否则null
Exceptions
Dart中所有的异常都是非受检异常。
throw是个表达式,不仅可以抛异常,还能抛其他任意对象。
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');
}
try {breedMoreLlamas();} catch (e) {print('Error: $e'); // Handle the exception first.} finally {cleanLlamaStalls(); // Then clean up.}
Classes
// If p is non-null, set its y value to 4.p?.y =4;
?.
调用构造方法
Dart 2中new是可选的
在一个constant上下文中,const是可以省略的。
获取对象的类型
runtimeType参数,返回Type对象
实例变量
classPoint {num x;num y;}voidmain() {var point =Point(); point.x =4; // Use the setter method for x.assert(point.x ==4); // Use the getter method for x.assert(point.y ==null); // Values default to null.}
实例变量生成getter方法,非final实例生成get和set方法。
构造方法
默认构造方法都是有的;
默认构造方法就是名称和类名一样的,剩下的就需要使用命名构造方法。
命名构造方法
classPoint {num x, y;Point(this.x, this.y);// Named constructorPoint.origin() { x =0; y =0; }}
abstractclassDoer {// Define instance variables and methods...voiddoSomething(); // Define an abstract method.}classEffectiveDoerextendsDoer {voiddoSomething() {// Provide an implementation, so the method is not abstract here... }}
;代替方法体即可。
每个类有个隐试的接口,神奇吧?
重载运算符
Dart支持重载运算符
classVector {finalint x, y;Vector(this.x, this.y);Vectoroperator+(Vector v) =>Vector(x + v.x, y + v.y);Vectoroperator-(Vector v) =>Vector(x - v.x, y - v.y);// Operator == and hashCode not shown. For details, see note below.// ···}
var names =<String>['Seth', 'Kathy', 'Lars'];var pages =<String, String>{'index.html':'Homepage','robots.txt':'Hints for web robots','humans.txt':'We are people, not machines'};
泛型方法
Tfirst<T>(List<T> ts) {// Do some initial work or error checking, then...T tmp = ts[0];// Do some additional checking or processing...return tmp;}
异步支持
FuturecheckVersion() async {var version =awaitlookUpVersion();// Do something with version}
为了使用await,代码必须要在一个async的函数中。
声明异步函数
Future<String> lookUpVersion() async=>'1.0.0';
使用了async关键字,那么函数返回得是Future类型.
处理流
当需要从流中获取值时,有两种方法:
1. 使用async和一个异步的循环(await for) 2. 使用Stream API
awaitfor (varOrType identifier in expression) {// Executes each time the stream emits a value.}Futuremain() async {// ...awaitfor (var request in requestServer) {handleRequest(request); }// ...}
classWannabeFunction {call(String a, String b, String c) =>'$a$b$c!';}main() {var wf =newWannabeFunction();var out =wf("Hi","there,","gang");print('$out');}