Riyad Zaigirdar
Riyad Zaigirdar

Reputation: 750

Dart: The argument type Object? cant be assigned to the parameter type 'double'

I have a Class Named FoodData which has required properties name, brand, price, image. All of the properties are String typed except price which is double.

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,
  });
}

I have a array of food data which is a list of objects containing food data...

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"
  }
]

My Goal is to loop through this array and initialize FoodData object through each iteration.

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
  ];
}

But it keeps saying on those 4 line when initializing (The argument type Object? cant be assigned to the parameter type 'double')....

I am new to flutter so please be kind and provide descriptive answers. Also it would be nice to suggest me some blogs.

Upvotes: 0

Views: 472

Answers (2)

AL.Sharie
AL.Sharie

Reputation: 1615

you can do this

  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 
      )
    );

  }

Upvotes: 1

Rahul
Rahul

Reputation: 5049

You need to provide the data-type while creating list of items

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"
  }
];

By default it's taking type of each item as ConstantStringMap<String, Object>

For more info : https://dart.dev/tools/diagnostic-messages#argument_type_not_assignable

Upvotes: 1

Related Questions