【发布时间】:2021-09-30 08:06:03
【问题描述】:
我有一个名为 FoodData 的类,它具有所需的属性名称、品牌、价格、图像。除 price 为 double 外,所有属性均为 String 类型。
class FoodData {
final String name;
final String brand;
final double price;
final String image;
const FoodData({
required this.name,
required this.brand,
required this.price, <-- double
required this.image,
});
}
我有一组食物数据,它是包含食物数据的对象列表...
const FOOD_DATA = [
{
"name":"Burger",
"brand":"Hawkers",
"price":2.99,
"image":"burger.png"
},
{
"name":"Cheese Dip",
"brand":"Hawkers",
"price":4.99,
"image":"cheese_dip.png"
},
{
"name":"Cola",
"brand":"Mcdonald",
"price":1.49,
"image":"cola.png"
}
]
我的目标是遍历这个数组并在每次迭代中初始化 FoodData 对象。
List<FoodData> getFoodData(){
List<FoodData> arr = [];
for (var i = 0; i < FOOD_DATA.length; i++) {
var item = FOOD_DATA[i];
var name = item["name"];
var brand = item["brand"];
var price = item["price"];
var image = item["image"];
arr.add(
FoodData(
name: name, <-- this line gives error
brand: brand, <-- this line gives error
price: price, <-- this line gives error
image: image <-- this line gives error
)
);
}
return [
...arr
];
}
但是在初始化的时候那4行一直说(参数类型Object?不能分配给参数类型'double')......
我是 Flutter 的新手,所以请善待并提供描述性的答案。也很高兴向我推荐一些博客。
【问题讨论】: