I have an array with such data (more data in reality)
[
{
serviceid: "979cf8e6",
amount: 1,
price: 11,
materialsPrice: 100,
enable: true,
chenge: true
},
{
serviceid: "979cf812",
amount: 1,
price: 15.5,
materialsPrice: 0,
enable: true,
chenge: true
}
]
I want to match all "price" in an array in which change = true. Now I'm using this query for this.
double get sumPay {
double sum = listVariant
.map((e) => e.price )
.fold(0, (previousValue, price) => previousValue price!);
return sum;
}
But this request sums up all the elements, and it will give me only those in which the status is change: true. I will be grateful for your help)
CodePudding user response:
Try this
double get sumPay {
var changeList = listVariant.where((e) => e.change == true);
double sum = changeList
.fold(0, (previous, next) => previous.price next.price);
return sum;
}
CodePudding user response:
Before calling map
funcrion use where
funtion to select what you want:
double get sumPay {
double sum = listVariant
.where((e) => e.change == true)
.map((e) => e.price )
.fold(0, (previousValue, price) => previousValue price!);
return sum;
}
CodePudding user response:
Try below code:
void main() {
List total = [
{
'serviceid': "979cf8e6",
'amount': 1,
'price': 11,
'materialsPrice': 100,
'enable': true,
'chenge': true
},
{
'serviceid': "979cf812",
'amount': 1,
'price': 15.5,
'materialsPrice': 0,
'enable': true,
'chenge': true
}
];
var count = total.map((m) => m["price"]).reduce((a, b) => a b);
print(count );
}
CodePudding user response:
You can check if chenge
is true
pass price
if not pass 0
, so change this
double sum = listVariant
.map((e) => e.price )
.fold(0, (previousValue, price) => previousValue price!);
to
double sum = listVariant
.map((e) => e.chenge ? e.price : 0) //<--- add this
.fold(0, (previousValue, price) => previousValue price!);
or as @pskink mentions use where
, like this:
double sum = listVariant
.where((e) => e.chenge)
.map((e) => e.price)
.fold(0, (previousValue, price) => previousValue price!);