skip to Main Content

I have a response from Api, like this(data[‘list’]):

[
  {
    id: 19d4ab3b8d64c,
    score: 70,
    startTime: null,
  },
  {
    id: 91e42b080ed6,
    score: 55,
    startTime: null,
  }
]

And I want to map data from data api to be like this:

List<TimeSeriesValues> data = [
  TimeSeriesValues(DateTime(2022, 2, 1, 00, 00), 30), // DateTime = startTime, 30 = score
  TimeSeriesValues(DateTime(2022, 2, 2, 23, 59), 80), // DateTime = startTime, 80 = score
];

But is startTime is null than we get current time and then add 24 hours duration to next element of data.

I tried to make it, but it looks bad, like this:

List<TimeSeriesValues> list = [];

if (data['list'][0]['startTime'] == null) {
  list.add(TimeSeriesValues(DateTime.now(), int.parse(data['list'][0]['score'])));
} else {
  list.add(TimeSeriesValues(data['list'][0]['startTime'], 0));
}

if (data['list'][1]['startTime'] == null) {
  list.add(TimeSeriesValues(DateTime(2022, 2, 1, 00, 00).add(const Duration(hours: 24)), int.parse(data['list'][1]['score'])));
} else {
  list.add(TimeSeriesValues(data['list'][1]['startTime'], 0));
}

I want to improve it, how can I do this?

2

Answers


  1. Try this:

    List<TimeSeriesValues> list = data['list'].map((e){
      if (e['startTime'] == null){
          list.add(TimeSeriesValues(DateTime.now(), int.parse(e['score'])));
      } else{
        list.add(TimeSeriesValues(DateTime.parse(e['startTime']), 0));
      }
    });
    
    Login or Signup to reply.
  2. You can try this:

    List<TimeSeriesValues> result = (data["list"] as List)
        .mapIndexed(
            (index, e) => TimeSeriesValues(e["startTime"] ?? DateTime.now().add(Duration(hours: index * 24)), int.parse(e['score'])))
        .toList();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search