1 函数定义
(1) 普通函数
返回值 函数的名称(参数列表) {函数体return 返回值}
示例:
int sum(int num1, int num2) {return num1 + num2;}// 也可简写为sum(num1, num2) {return num1 + num2;}
(2) 箭头函数
这里面只能是一个表达式, 不能是一个语句
sum(num1, num2) => num1 + num2;
(3) 匿名函数
void main(List<String> args) {// 实名函数test(bar);// 匿名函数test(() {print("匿名函数被调用");});// 匿名箭头函数test(() => print("匿名箭头函数被调用"));}// 接收一个函数作为参数void test(Function foo) {foo();}void bar() {print("bar函数被调用");}
2 可选参数
(1) 可选位置参数
// 可选位置参数void sayHello(String name, [int age=10, double height=1.60]) {print(name.toString() + height.toString());}// 可选位置参数必须按顺序传, 不能先传height, 再传agesayHello("张三");sayHello("张三", 28);sayHello("张三", 28, 1.64);
(2) 可选命名参数
// 可选命名参数,void sayHello2(String name, {int age, double height=1.60}) {print(name.toString() + height.toString());}// 可以对{}中任意位置的参数进行传参sayHello2("gates", height: 1.85);
3 函数别名
typedef Calculate = int Function(int, int);
