飞镖的构造函数无效
请告诉我。为什么默认情况下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
Tell me please. Why is pr2 null and not str1 by default?
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');
}
}
The pr1: 4 The pr2: null The pr3: 5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为默认情况下,可选参数是
null
,除非在构造函数定义中另有说明。如果要声明另一个默认值,则需要使用此语法:Because optional parameters are by default
null
unless otherwise specified in the constructor definition. If you want to declare another default value, you need to use this syntax:我对您的代码进行了重新分配以确保可读性,并将使用上述IF-ELSE语句删除第一个解决方案
,您可以看到,当Pr2的条件为null时,它将显示文本“ str1”,如果不是null,则显示PR2的值。
希望这有帮助。
I refactored your code for readability and would drop the first solution using if-else statement
From the above, you can see that when the condition for pr2 is null, it displays the text 'str1' and if it is not null, it displays the value of pr2.
Hope this helps alot.
第二种方法是使用终止操作员检查null
是否含义是什么意思?简而言之,将其视为逻辑条件,一种if-else的形式,但以一种更简单的方式表达出来的方法是:
如果条件为真,则表达式1运行,如果条件为false,则表达式2运行。
为了回答您的问题,从Dart 2.12开始,它变得无效,这不是变量到构造函数的安全做法。我很高兴进一步解释是否需要。
The second way would be to use a tenary operator to check for null
What does tenary mean? simply put, think of it as a logic condition, a form of if-else but in an easier way, the way to express this is:
if the condition is true, expression 1 runs, if the condition is false, expression 2 runs.
To answer your question, from dart 2.12, it became null safe, it is not a safe practice to variables to constructors. I would be glad to explain further if the need be.