Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to map data from api in flutter?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading