I have an error inside my project
total += double.parse(value.price!) * value.quantity;
in this line, the error occurs
The argument type ‘int?’ can’t be assigned to the parameter type
‘num’.
cart_provider.dart
import 'package:flutter/foundation.dart';
import 'package:myproject/model/CartModel.dart';
class Cart with ChangeNotifier {
Map<String, CartModel> _items = {};
Map<String, CartModel> get items {
return {..._items};
}
void addItem({required String productId,price,title,name,image,quantity}){
if(_items.containsKey(productId)){
_items.update(productId, (value) => CartModel(
key: value.key,
name:value.name,
image:value.image,
price:value.price,
quantity:value.quantity! + 1,
totalPrice:value.totalPrice,
));
notifyListeners();
}else{
_items.putIfAbsent(productId, () => CartModel(
key:DateTime.now().toString(),
name:name,
image:image,
price:price,
totalPrice:0,
quantity: 1,
));
notifyListeners();
};
}
double get totalToPay{
double total = 0.0;
_items.forEach((key, value) {
total += double.parse(value.price!) * value.quantity;
});
return total;
}
}
Here is my cartModel.dart
class CartModel {
String? key;
String? name;
String? image;
String? price;
int? quantity;
double? totalPrice;
CartModel(
{required this.key,
required this.name,
required this.image,
required this.price,
required this.quantity,
required this.totalPrice});
CartModel.fromJson(Map<String, dynamic> json) {
key = json['key'];
name = json['name'];
image = json['image'];
price = json['price'];
quantity = json['quantity'] as int;
totalPrice = double.parse(json['totalPrice']);
}
Map<String,dynamic> toJson(){
final Map<String,dynamic> data = new Map<String,dynamic>();
data['key'] = this.key;
data['name'] = this.name;
data['image'] = this.image;
data['price'] = this.price;
data['quantity'] = this.quantity;
data['totalPrice'] = this.totalPrice;
return data;
}
}
2
Answers
In your CartModel
int? quantity
is nullable, so you have to use a null check onvalue.quantity
.Try
value.quantity
can get null and using null-assert (!
) have some risk. Also a better way of parsing double from string will be using.tryParse
which handle exception.