0

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?

1
  • could you include TimeSeriesValues class? Commented Dec 7, 2022 at 15:09

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

Comments

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));
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.