请告诉我。为什么默认情况下pr2为null而不是str1?
void main() {
var house = Home(pr1: 4, pr3: 5);
house.printDate();
}
class Home {
int pr1=1;
String? pr2 = 'str1';
int pr3=3;
Home({required this.pr1, this.pr2, required this.pr3});
void printDate() {
print('The pr1: $pr1');
print('The pr2: $pr2');
print('The pr3: $pr3');
}
}pr1: 4 pr2: null pr3: 5
发布于 2022-06-22 14:03:09
因为默认情况下,可选参数是null,除非构造函数定义中另有规定。如果要声明另一个默认值,则需要使用以下语法:
void main() {
var house = Home(pr1: 4, pr3: 5);
house.printDate();
// The pr1: 4
// The pr2: str1
// The pr3: 5
}
class Home {
int pr1=1;
String? pr2;
int pr3=3;
Home({required this.pr1, this.pr2 = 'str1', required this.pr3});
void printDate() {
print('The pr1: $pr1');
print('The pr2: $pr2');
print('The pr3: $pr3');
}
}发布于 2022-06-22 14:59:32
为了提高可读性,我重构了您的代码,并使用if-else语句删除了第一个解决方案。
class Home {
//initialize the variables using the final keyword
final int? pr1;
final String? pr2;
final int? pr3;
//set the constructors
Home({required this.pr1, this.pr2, required this.pr3});
void printDate(){
//using the pr1 value
print('The pr1: $pr1');
//perfoming a runtime assertation for dev
//assert(pr2 == null);//if the value for pr2 is null; it run smoothly
//using if-else statement, I can tell wht is shows as outcome
if (pr2 == null){
print('The pr2: str1');
}else{print('The pr2: $pr2');}//I would be rewriting this as a tenary operator
//using the pr3 value
print('The pr3: $pr3');
}
}
//the app starts ro run from here
void main(){
var house = Home(pr1:5,pr3:6,);
house.printDate();
}从上面可以看到,当pr2的条件为null时,它将显示文本'str1‘,如果它不是null,则显示pr2的值。希望这能帮上很多忙。
发布于 2022-06-22 15:21:14
第二种方法是使用tenary运算符检查空值。
class Home {
//initialize the variables using the final keyword
final int? pr1;
final String? pr2;
final int? pr3;
//set the constructors
Home({required this.pr1, this.pr2, required this.pr3});
void printDate() {
//using the pr1 value
print('The pr1: $pr1');
//pr2 check for null safety using tenary
pr2 == null ? print('The Pr2: str1'):print('The pr2:$pr2');
//using the pr3 value
print('The pr3: $pr3');
}
}
//the app starts ro run from here
void main() {
var house = Home(
pr1: 5,
pr3: 6,
);
house.printDate();
}十元是什么意思?简单地说,把它看作是一种逻辑条件,一种如果
condition?expression1:expression2;如果条件为真,则表达式1运行,如果条件为false,则表达式2运行。要回答您的问题,从第2.12段开始,它变成了空安全,对于构造函数的变量来说,这不是一个安全的实践。如有需要,我乐意作进一步解释。
https://stackoverflow.com/questions/72716451
复制相似问题