I have a cart and I want to assign my cart items to my _items variable inside my Provider.
This is my method. I don’t know if I should use toJson() or fromJson() methods:
This is the variable and the function inside the provider:
Map<String, CartItem> _items = {};
void getItems()async {
var newItems = await FirebaseFirestore.instance.collection("users").doc(userId).collection("Cart").get();
_items = newItems; // The error occurs here
}
Error:
A value of type ‘QuerySnapshot<Map<String, dynamic>>’ can’t be assigned to a variable of type ‘Map<String, CartItem>’.
Try changing the type of the variable, or casting the right-hand type to ‘Map<String, CartItem>’.
CartModel.dart
class CartItem {
String? id;
String? title;
String? price;
int? qty;
String? image;
CartItem({
required this.id,
required this.title,
required this.price,
required this.qty,
required this.image,
});
CartItem.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
image = json['image'];
price = json['price'];
qty = json['qty'] as int;
// totalprice = double.parse(json['totalprice']);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['title'] = this.title;
data['image'] = this.image;
data['price'] = this.price;
data['qty'] = this.qty;
// data['totalprice'] = this.totalprice;
return data;
}
}
Because I want to use it here (no space to. I will share a snippet):
2
Answers
I think toJson is if you’re trying to send it out as json. From json is if you expect to receive that data (like an API get request).
The error comes from you declaring _items to be of type Map<String, CartItem> but in the CartModel class, it is expected to come in as as Map of string to string.
fromjson
method should return a class instance.Below is your updated class:
Now to fix the above error, we have to convert
QuerySnapshot<Map<String, dynamic>>
toMap<String, CartItem>
.Note: I’ll use
List<CartItem>
instead ofMap<String, CartItem>
.This code was not tested.