Flutter 函数的基本使用
声明
返回值类型 函数名称(参数列表){函数体;return 返回值;}
void 函数名称(参数列表){函数体;}
例如:
int max(int a, int b) {int result;if (a > b) {result = a;} else {result = b;}return result;
}
可选的命名参数
声明定义方法:{参数类型? 参数名,参数类型?参数名}
调用:“参数名:值”
void main() {printInt();printInt(str: "111");//可选参数指定实参printInt2();
}void printInt({String? str, String? srt2}) {print(str);
}//有默认值
void printInt2({String? str = "222", String? srt2}) {print(str);
}I/flutter ( 7019): null
I/flutter ( 7019): 111
I/flutter ( 7019): 222
可选的位置参数
声明定义方法:[参数名,参数名]
调用方法:“值”
void main() {printMM(1);printMM(1,20);printMM2();
}void printMM([int? a, int? b]){print(a);
}
//有默认值
void printMM2([int? a = 100, int? b]){print(a);
}I/flutter ( 7019): 1
I/flutter ( 7019): 1
I/flutter ( 7019): 100
匿名函数
void main() {() {print("匿名函数");}();(int a) {print("有参数的匿名函数$a");}(50);var x = () {print("有返回值值的匿名函数");return "返回值";}();print(x);
}I/flutter ( 7019): 匿名函数
I/flutter ( 7019): 有参数的匿名函数50
I/flutter ( 7019): 有返回值值的匿名函数
I/flutter ( 7019): 返回值
箭头函数
/*int max(int a, int b) {return a > b ? a : b;
}*/
等同
int max(int a, int b) => a > b ? a : b;
闭包函数
(1)内部函数为有参数的匿名函数
void main() {var result = test();print(result(2.0));// 12.56
}Function test() {const PI = 3.14;return (double r) => r * r * PI;
}
(2)内部函数为无参数的匿名函数
void main() {var result = test();print(result());
}Function test() {const PI = 3.14;return () => PI;
}
异常
(1)抛出异常
void main() {throwMyException();
}void throwMyException(){throw "这是一个异常";
}
E/flutter ( 7019): [ERROR:flutter/runtime/dart_vm_initializer.cc(40)] Unhandled Exception: 这是一个异常
E/flutter ( 7019): #0 throwMyException (package:first_flutter/main.dart:86:3)
E/flutter ( 7019): #1 main (package:first_flutter/main.dart:81:3)
E/flutter ( 7019): #2 _runMain.<anonymous closure> (dart:ui/hooks.dart:320:23)
E/flutter ( 7019): #3 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:314:19)
E/flutter ( 7019): #4 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:193:12)
(2)捕获异常 try-catch-finally
不会中断执行
void main() {List lists = [1, 2];print(lists[0]);try{print(lists[2]);}catch(e){}print(lists[1]);
}I/flutter ( 7019): 1
I/flutter ( 7019): 2