假設我有一個物件,例如:
class Fruit{
String? name;
int? quantity;
String? color;
}
Fruit exampleFruit = Fruit(name: 'Apple', quantity: 3, color: 'red');
我列印出所有鍵值對的最有效方法是什么?
我想到的偽代碼:
exampleFruit.keys.forEach((key){
Text(key);
}
澄清一下,這個問題的原因是我有一個物件,其中一些屬性可以為空。在顯示這些屬性的那一刻,我想知道是否可以通過映射所有現有的鍵值對而不是檢查 null 然后顯示
uj5u.com熱心網友回復:
好吧,您可以在類中創建一個toJson方法Fruit,并始終列印出您的引數:
class Fruit {
final String? name;
final int? quantity;
final String? color;
const Fruit({
this.color,
this.name,
this.quantity,
});
Map<String, dynamic> toJson() => {
if(name != null) "name": name,
if(quantity != null) "quantity": quantity,
if(color != null) "color": color,
};
}
接著 :
Fruit exampleFruit = Fruit(name: 'Apple', quantity: 3, color: 'red');
print(exampleFruit.toJson()); // prints {name: Apple, quantity: 3, color: red}
uj5u.com熱心網友回復:
你可以像這樣在地圖中:
void main() {
final testMap = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5};
for (final mapEntry in testMap.entries) {
final key = mapEntry.key;
final value = mapEntry.value;
print('Key: $key, Value: $value'); // Key: a, Value: 1 ...
}
}
但是對于您的物件,您可以宣告一個 getter :
class Vehicle {
String make;
String model;
int manufactureYear;
int vehicleAge;
String color;
int get age {
return vehicleAge;
}
void set age(int currentYear) {
vehicleAge = currentYear - manufactureYear;
}
// We can also eliminate the setter and just use a getter.
//int get age {
// return DateTime.now().year - manufactureYear;
//}
Vehicle({this.make,this.model,this.manufactureYear,this.color,});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/412690.html
標籤:
