函数简单使用
我们定义一个函数,并调用看看
// 一切都是对象
->「这个Function方法没办法表示传入的参数,返回值是什么」
void fun(Function f) {
f(1,2);
}
void main() {
Function f = fun;
->「这里是传入一个闭包closure,也可以叫lambada,匿名函数等」
f((int i, int j) {
return "1";
});
}
但是这么做似乎,调用者很茫然,他相当于这么定义
void fun3(void f1(int i, int j)) {}
但dart里面里有更好的方式:「typedef 定义一个函数类型」
typedef String F(int i, int j);
String fun4(F f) {
return f(1, 1);
}
应用场景
// 对比java,需要定义一个接口,然后传入接口
class OnCicklistener {
void onClick() {}
}
class Button {
void setOnClicklistener(OnCicklistener onCicklistener) {}
}
// dart 定义一个函数,传函数
typedef void onClick();
class Button2 {
void setOnClicklistener(onClick listener) {
listener();
}
}
可选位置参数
// 可选位置参数
-> 「理解上可以想象数组,按顺序传递参数,也可以给默认的值」
void fun5([int i,int j = 2]){
print(i);
print(j);
}
调用可以,如下
fun5(3);
fun5(3,5);
可选命名参数
// 可选命名参数
-> 这个参数传值不考虑顺序,但是每个参数必须K:V 的方式传值,可以有默认值
void fun6({int i,int j = 2}){
print(i);
print(j);
}
调用 ->
fun6(i:3,j:0);
fun6(j:6,i:300);
应用场景:不需要写大量的重载函数,类似java一样,可以给默认值
比如构造函数,dart一个方法搞定一切
异常
「需要注意的是」->Dart & Kotlin 类似,不会主动提示你try-catch,需要你自己添加
作为实验,我们定义几个函数
void testStr(String str){
print(str);
}
void test(){
throw Exception("你太帅不给你调用");
}
void test2(){
throw "你太帅不给你调用";
}
void test3(){
throw 111;
}
int test4(int i){
if(i == 0){
throw "000000";
} else if(i == 1) {
throw 1;
} else if(i == 2){
throw testStr;
}
->「抛出异常还可以返回」
return i;
}
catch 最多接受两个参数,exception & stack
try {
test();
->「exception,StackTrace」
} catch (e,s) {
print(e);
print(e.runtimeType);
print(s);
print(s.runtimeType);
}
按照异常类型进行过滤处理
-> on Type catch...
try {
// test();
// test2();
test3();
} on Exception catch (e,s) {
print("Exception......lll");
print(e);
print(e.runtimeType);
print(s);
print(s.runtimeType);
} on int catch(e) {
print("int");
print(e);
} on String catch(e){
print("String");
print(e);
}
捕获异常可以继续调用函数处理
try {
int i = test4(3);
if(i == 3) {
print('return .......');
}
} on Function catch (e,s) {
e("骚操作");
} on String catch(e) {
print(e);
} on int catch(e){
print(e);
} finally{
-> 「最终这里执行,和java一样」
}