New to Dart (Flutter), and the docs don't seem to have a method for the Map class that will allow me to do this easily...
I want to have a Map with keys of Datetime and values of calories eaten.
{'2019-07xxx': 350, '2019-07xxx': 500, ...}
Now, what's the best way to filter this so that I only get values from today? (i.e. when starting the app and pulling the data from storage)
Ideally once I do that, I can get the cumulative value of today's calories so far with:
var sum = todaysCaloriesArray.reduce((a, b) => a + b);
Unless there is some Dart-fu that would allow this in a better way?
You could use .where
on the map's entries
. For example:
var map = Map<String, int>();
var sum = map.entries
.where((e) => e.key.startsWith('2019-07-22'))
.map<int>((e) => e.value)
.reduce((a, b) => a + b);
The first answer was great! But you can use the fold
method so you can use in empty collections.
var map = Map<String, int>();
var sum = map.entries
.where((e) => e.key.startsWith('2019-07-22'))
.fold(0,(int a, b) => a + b.value);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With