請告訴我。為什么 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
uj5u.com熱心網友回復:
因為可選引數是默認的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');
}
}
uj5u.com熱心網友回復:
我重構了您的代碼以提高可讀性,并會使用 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的值。希望這有很大幫助。
uj5u.com熱心網友回復:
第二種方法是使用三元運算子來檢查 null
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();
}
一元是什么意思?簡單地說,將其視為邏輯條件,if-else 的一種形式,但以更簡單的方式表達它的方式是:
condition?expression1:expression2;
如果條件為真,則運算式 1 運行,如果條件為假,則運算式 2 運行。為了回答你的問題,從 dart 2.12 開始,它變成了 null 安全的,將變數傳遞給建構式不是一種安全的做法。如果需要,我很樂意進一步解釋。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/494742.html
下一篇:如何將檔案快照作為串列獲取
