Dart 方法

同一作用域中,不允许重复定义名称一样的方法

//不规定是否有返回值,dart编译时自动识别
fun_1(){  print('hi'); }
fun_2(){  return 'hi'; }
// 胖箭头函数必有返回值,若表达式没有返回值则返回null
fat_fun()=>print('hi');
// 确定唯一返回值
int add(int? a,int? b){
  return (a??0)+(b??0);
}
// 返回值类型不唯一(可能string,int,double,object)
dynamic fun_order(int i){
  switch (i){
    case 1: return 1;break;//返回int型
    case 2:return 'hi';break;//返回string型
    case 3:return Jack(name: 'jack', age: 19);//返回object型
    case 4:return 3.14;//返回double型
    default: break;
  }
}

最普通的用法

fun_0(int a,int b,int c,int d,int e){
  print('$a $b $c $d $e');
}

默认值

// 默认值,参数必须放在[]中,
fun_1([int a = 1,int b = 2,int c = 3,int d = 4, int e = 5]){
  print('$a $b $c $d $e');
}

Dart的方法,不允许将上述两种模式混用,如下

// 这种是严重错误的!
fun_1([int a =1,int b=2,int c=3],int d,int e){
    
}

具名参数

方法的参数是具名参数,则必须注意“空安全”的问题!

fun_3({int? a,int? b,int? c}){
  print('$a $b $c');
}
// 调用
fun_3(a:1,b:3,c:4);
posted @ 2023-03-16 11:19  勤匠  阅读(16)  评论(0编辑  收藏  举报