Home > Mobile >  How to fix mapIndexed function in flutter?
How to fix mapIndexed function in flutter?

Time:12-08

I have a function that map from one list and add every item to another list:

List<TimeSeriesValues> list = (data["list"] as List).mapIndexed(
  (index, e) => TimeSeriesValues(DateTime.tryParse(e["detectedAt"])!,int.parse(e['score']))).toList();

This is TimeSeriesValues class:

class TimeSeriesValues {
  final DateTime time;
  final int values;

  TimeSeriesValues(this.time, this.values);
}

And I want to add if statements, like if e['score'] != 0 then we add the item to the list otherwise not.

If e['score'] != 0 then add TimeSeriesValues(DateTime.tryParse(e["detectedAt"])!, int.parse(e['score'])) to list else not

This is the response from Api:

[{detectedAt: 2022-11-28T00:00:00.000Z, score: 57},...] // data['list']

CodePudding user response:

Try this:

List<TimeSeriesValues> list = (data["list"] as List).mapIndexed(
  (index, e) => TimeSeriesValues(DateTime.tryParse(e["detectedAt"])!,int.parse(e['score']))).toList();
List<TimeSeriesValues> filteredList = list.where((e) => e.values != 0).toList();

CodePudding user response:

Simply use for each loop as following

List<TimeSeriesValues> list = [];
  (data["list"] as List).forEach((e){
if(int.parse(e['score']) != 0){ list.add(TimeSeriesValues(DateTime.tryParse(e["detectedAt"])!,int.parse(e['score'].toString()))); }
      }); 
  • Related