Dart:参数类型对象?不能分配给参数类型“double”

时间:2021-07-23 06:43:07

标签: flutter dart

我有一个名为 FoodData 的类,它具有所需的属性名称、品牌、价格、图像。除了双倍的价格外,所有的属性都是字符串类型的。

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 的新手,所以请善待并提供描述性的答案。也很高兴向我推荐一些博客。

2 个答案:

答案 0 :(得分:1)

您需要在创建项目列表时提供数据类型

const FOOD_DATA = <Map<String, dynamic>>[
  {
    "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"
  }
];

默认情况下,每个项目的类型为 ConstantStringMap<String, Object>

更多信息:https://dart.dev/tools/diagnostic-messages#argument_type_not_assignable

答案 1 :(得分:1)

你可以这样做

  for (var i = 0; i < FOOD_DATA.length; i++) {
    var item = (FOOD_DATA[i]);

    var name = item["name"] as String;
    var brand = item["brand"] as String;
    var price = item["price"] as double;
    var image = item["image"] as String;
    
    arr.add(
      FoodData(
        name: name,
        brand: brand,
        price: price, 
        image: image 
      )
    );

  }