命名参数
在类似于java,php,c++ 等高级语言中,函数的定义和抽象基本如下:
//定义
int achievement(int Chinese ,int Mathematics){
return Chinese+Mathematics ;
}
//调用
//调用时,就已经定死了,前面的这个参数是语文成绩,后边是数据成绩。感觉像是一个队列形式的传参方式,且此队列顺序不可乱。
int result = functionPlus(99,89);
在使用Dart时,有一种类似于Map传形式的参方式:命名参数。
//函数的定义:
int achievement({int chinease ,int mathMatic}){
print('chinease -> $chinease , mathMathic -> $mathMatic') ;
return chinease + mathMatic ;
}
//函数调用:
achievement(chinease: 21 , mathMatic: 39);
achievement(mathMatic: 39 , chinease: 21) ;
好处在于,我们可以使用类似于键值的形式去传参
1.代码阅读性强
2.参数传递顺序不受限
当然我们也可以使用正常的方式
定义:
int achievementNormal(int chin ,int math){
print("chiniease -> $chin mathMatic -> $math" );
return chin + math ;
}
//调用
achievementNormal(20, 30) ;
必传参数@required
如果有参数是必传,我们可以在函数定义的时候,使用@required来修饰:
//函数的定义:
int achievement({int chinease ,@required int mathMatic}){
print('chinease -> $chinease , mathMathic -> $mathMatic') ;
return chinease + mathMatic ;
}
可选参数
Dart还给我们准备了可选参数:
//定义 ,普通的函数|方法定义
int achievementNormal(int chin ,int math , [int history]){
print("chiniease -> $chin mathMatic -> $math history-> $history" );
return chin + math ;
}
//调用
achievementNormal(20, 30 ,20) ;
achievementNormal(20, 33) ;
但是可惜的是,通过测试,在命名参数形式中,不能使用可选参数。即:必传参数和可选参数不可共同出现在一个方法|函数中。
参数默认值
//为命名参数设置默认值的示例
void enableFlags({bool bold = false, bool hidden = false})
{...}
//设置位置参数的默认值
String say(String from, String msg, [String device = 'carrier pigeon', String mood])
{...}
//还可以将列表或map集合作为默认值
void doStuff({List<int> list = const [1, 2, 3],
Map<String, String> gifts = const {
'first': 'paper',
'second': 'cotton',
'third': 'leather'
}})
{...}
注意:
1.默认值必须是编译时常量
2.如果没有提供默认值,则默认值为null
3.建议您使用’=’来指定默认值
暂无评论
要发表评论,您必须先 登录