skip to Main Content

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']

2

Answers


  1. 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();
    
    Login or Signup to reply.
  2. 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()))); }
          }); 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search