How to iterate through a dynamic list of objects in dart

Viewed 3090

I have this dynamic list which I am decoding from a json response, it goes as

[{Calcium: [47.92, mg, Red, 0.00169033008, ounce]}, {Choline: [71.88, mg, Red, 0.00253549512, ounce]}, {Copper: [0.08, mg, Red, 0.00000282192, ounce]}, {Crude fat: [70.28, g, Green, 2.47905672, ounce]}, {Folate: [23.96, mcg, Red, 0.00000084516504, ounce]}...]

In that I need to check whether a given key exists. for an example check key "Calcium" exists and if so I need to fetch the value of index 0 and index 2 of the array belongs to that key, I want to perform this in an iterative way.

how can I achieve this in dart?

I have tried this but it does not work , maybe I'm doing it in a wrong way.

nutrientList.forEach((element) {

        if(nutrientList.contains("Calcium")) {
          valCalcium = element.calcium[0];
          calciumClr = element.calcium[2];
        } else {}
1 Answers

You can create an Object that maps the Json object to the values you need. Let Calcium be an object that parses "Calcium". Since the Map has dynamic as its values, it can handle a List value.

class Calcium {
  final List<String> content;

  Calcium({
    required this.content,
  });

  factory Calcium.fromJson(Map<String, dynamic> json) {
    return Calcium(
      content: json['Calcium'],
    );
  }
}

Then to fetch the details inside the Object, parse the json response with Calcium.fromJson() then get List by calling Calcium.content

Calcium calcium = Calcium.fromJson(json);
List<String> calciumDetails = calcium.content;
Related