函数
因为函数也是对象,所以当没有返回值的时候,函数的对象的值就是null
函数创建
dart的类跟java的类在定义上面十分的相似
class Point{
int x;
}
构造函数
简单构造函数
class Point{
int x;
Point(x){
this.x = x;
}
}
语法糖
当构造函数中传递的参数是给类里面的值直接赋值的时候,可以在变量名上使用this的关键字来直接接受值
class Point{
int x;
Point(this.x){}
}
当调用Point point = new Point(12),这个小point的x就直接赋予了12这个值
命名构造函数
使用类.方法名称来定义指定名称的构造函数
class Point{
int x;
Point(int a){
this.x = a;
}
Point.newInstance(int a){
this.x = a;
}
}
// 使用Point.newInstantce()来调用,获取对象的实例对象
语法糖
高版本实例化可以省略new关键字
// 原来
Point point = new Point();
//可以省写
Point point = Point();
函数类型
匿名函数
省略掉方法名称
list.forEach((item){
print('hello')
})
匿名函数简写
当只有一行代码的时候,就不要{},直接使用 => 后面跟一行表达式即可,当超过一行表达式的时候,需要使用上面的方式
list.forEach(item => print('hello'))
函数参数
可选参数
使用{param1,param2}来指明
void enableFlags({bool bold,bool hidden})
默认参数
直接在后面跟=赋值即可
void enableFlags({bool bold=false,bool hidden=true})
作用域
以_开头的表示私有,其余都正常
函数调用
级联调用
querySelector('#confirm') // Get an object.
..text = 'Confirm' // Use its members.
..classes.add('important')
..onClick.listen((e) => window.alert('Confirmed!'));
等价于
var button = querySelector('#confirm');
button.text = 'Confirm';
button.classes.add('important');
button.onClick.listen((e) => window.alert('Confirmed!'));
非空调用
使用?.的方式来调用,可以避免左边操作符为null的情况
p?.y = 4;
函数对象调用
你可以将一个函数作为参数传递给另一个函数。暂时没找到比较有意义的写法,感觉就是在炫技