函数的基本使用
建议所有函数都声明返回类型,没有返回值声明 void 类型。
void printTitle(String title) {print('The title : ${title.toString()}');}String getName(String firstName, String lastName) {String res = 'my name is ${firstName}-${lastName}';printTitle(res);return res;}int getSum(int num) {int sum = 0;for (int i=1; i<=num; i++) {sum += i;}return sum;}
可选参数 和 默认参数
dart 中声明可选参数,需要在参数列表声明 List 格式的参数列表,表明是可选的。
// 可选参数 & 默认参数void printInfo(String name, [int age, String sex = '男']) {if(age == null) {print('my name is ${name}, sex is ${sex}');} else {print('my name is ${name}, age is ${age}, sex is ${sex}');}}printInfo('postbird'); // my name is postbird, sex is 男printInfo('postbird', 20); // my name is postbird, age is 20, sex is 男printInfo('postbird', 20, '女'); // my name is postbird, age is 20, sex is 女
命名参数
dart 可以指定参数名称,而不需要传入一个 Map 才能指定名称,这点非常实用
// 命名参数void printInfo2(String name, {int age, String sex = '男'}) {if(age == null) {print('my name is ${name}, sex is ${sex}');} else {print('my name is ${name}, age is ${age}, sex is ${sex}');}}
在 Flutter 中如果参数都使用命名参数,要指定某个参数是必须传递的,则需要通过 @required 注解
函数作为参数
void main(){executeFunction(fn, [args]) {if (fn != null) {return fn(args);}}}
箭头函数
void main(){List l1 = [1, 2];l1.forEach((item) {print(item);});l1.forEach((item) => print(item));}
匿名函数
Function getInfo = (String name, int age, [String sex = '男']) {print('My name is ${name}, my age is ${age}, my sex is ${sex}');};getInfo('postbird', 20);
立即执行函数
// 立即执行方法((name) {print('my name is ${name}');})('postbird');
闭包
// 闭包Function getA() {int a = 0;return () {a++;print(a);};}Function b = getA();b();b();
