函数的基本使用

建议所有函数都声明返回类型,没有返回值声明 void 类型。

  1. void printTitle(String title) {
  2. print('The title : ${title.toString()}');
  3. }
  4. String getName(String firstName, String lastName) {
  5. String res = 'my name is ${firstName}-${lastName}';
  6. printTitle(res);
  7. return res;
  8. }
  9. int getSum(int num) {
  10. int sum = 0;
  11. for (int i=1; i<=num; i++) {
  12. sum += i;
  13. }
  14. return sum;
  15. }

可选参数 和 默认参数

dart 中声明可选参数,需要在参数列表声明 List 格式的参数列表,表明是可选的。

  1. // 可选参数 & 默认参数
  2. void printInfo(String name, [int age, String sex = '男']) {
  3. if(age == null) {
  4. print('my name is ${name}, sex is ${sex}');
  5. } else {
  6. print('my name is ${name}, age is ${age}, sex is ${sex}');
  7. }
  8. }
  9. printInfo('postbird'); // my name is postbird, sex is 男
  10. printInfo('postbird', 20); // my name is postbird, age is 20, sex is 男
  11. printInfo('postbird', 20, '女'); // my name is postbird, age is 20, sex is 女

命名参数

dart 可以指定参数名称,而不需要传入一个 Map 才能指定名称,这点非常实用

  1. // 命名参数
  2. void printInfo2(String name, {int age, String sex = '男'}) {
  3. if(age == null) {
  4. print('my name is ${name}, sex is ${sex}');
  5. } else {
  6. print('my name is ${name}, age is ${age}, sex is ${sex}');
  7. }
  8. }

在 Flutter 中如果参数都使用命名参数,要指定某个参数是必须传递的,则需要通过 @required 注解

函数作为参数

  1. void main(){
  2. executeFunction(fn, [args]) {
  3. if (fn != null) {
  4. return fn(args);
  5. }
  6. }
  7. }

箭头函数

  1. void main(){
  2. List l1 = [1, 2];
  3. l1.forEach((item) {
  4. print(item);
  5. });
  6. l1.forEach((item) => print(item));
  7. }

匿名函数

  1. Function getInfo = (String name, int age, [String sex = '男']) {
  2. print('My name is ${name}, my age is ${age}, my sex is ${sex}');
  3. };
  4. getInfo('postbird', 20);

立即执行函数

  1. // 立即执行方法
  2. ((name) {
  3. print('my name is ${name}');
  4. })('postbird');

闭包

  1. // 闭包
  2. Function getA() {
  3. int a = 0;
  4. return () {
  5. a++;
  6. print(a);
  7. };
  8. }
  9. Function b = getA();
  10. b();
  11. b();