Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I filter List<Map<String, dynamic>> to get a value in Flutter?

I have a json data and I am loading into List<Map<String, dynamic>> using await jsonDecode..

Example, I have a;

  1. amount = 12500
  2. caliber = 24

and I need to filter the son to get maturity value: 689.19

Also if I have a amount = 12500 and value = 689.19 I need to get caliber which is 24.

How can I filter List> json data to get a value in Flutter?

[
   {"amount": "5000", "caliber": "12", "maturity":  "484.25"},
   {"amount": "5000", "caliber": "24", "maturity":  "275.67"},
   {"amount": "7500", "caliber": "12", "maturity":  "726.38"},
   {"amount": "7500", "caliber": "24", "maturity":  "413.51"},
   {"amount": "10000", "caliber": "12", "maturity":  "968.50"},
   {"amount": "10000", "caliber": "24", "maturity":  "551.35"},
   {"amount": "12500", "caliber": "12", "maturity":  "1210.63"},
   {"amount": "12500", "caliber": "24", "maturity":  "689.19"},
   {"amount": "15000", "caliber": "12", "maturity":  "1452.76"},
   {"amount": "15000", "caliber": "24", "maturity":  "827.03"},
   {"amount": "15000", "caliber": "12", "maturity":  "1694.89"},
   {"amount": "17500", "caliber": "24", "maturity":  "964.87"},
   {"amount": "17500", "caliber": "36", "maturity":  "727.66"},
   {"amount": "17500", "caliber": "48", "maturity":  "613.53"},
   {"amount": "17500", "caliber": "60", "maturity":  "548.44"},
   {"amount": "20000", "caliber": "12", "maturity":  "1937.01"},
   {"amount": "20000", "caliber": "24", "maturity":  "1102.71"}
]

UPDATE: With @Muldec help I finally got it.

First I load above son to List as shown below. And apply @Muldec answer and it worked.

List<Map> myList = List<Map>.from(jsonDecode(jsonFastCalculation) as List);
final item = myList.firstWhere((e) => e['amount'] == '12500' && e['caliber'] == '24');
print(item['maturity']);
like image 986
Nick Avatar asked Oct 24 '25 14:10

Nick


1 Answers

You can use the firstWhere or where methods on your list to get the Map element you need or a list of Map depending on your search criteria.

Supposing you are absolutely sure your search criteria will give you only one item (or that you only care of the first item meeting your criteria) here's an example of code with firstWhere:

List<Map<String, dynamic>> myList = ....;

final item = myList.firstWhere((e) => e['amount'] == '12500' && e['caliber'] == '24');
print(item['maturity']);

Finding the caliber based on the amount and the maturity is simply a mater of changing the test in the firstWhere method

like image 165
Muldec Avatar answered Oct 27 '25 05:10

Muldec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!