2

I would like to map the following json structure to models. I try to map the array to an List and than parse each set to model.

The following error would be displayed:

type 'MappedListIterable' is not a subtype of type 'List'


Json

  {
      "objectId": "vbbZIPV6qs",
      "sets": [
        {
          "repetitions": 10,
          "weight": 10,
          "time": 0
        }
      ],
      "description": "",
      "type": "EXERCISE",
    }

Flutter

class PlanItem {
  String type;
  String description;
  List<Set> sets = [];

  PlanItem(this.type, this.description, this.sets);

  factory PlanItem.fromJson(Map<String, dynamic> json) {
    return PlanItem(
      json['type'],
      json['description'],
      (json['sets'] as List).map((i) {
        return Set.fromJson(i);
      }).toList(),
    );
  }
}

class Set {
  int repetitions;
  int weight;
  int time;

  Set(this.repetitions, this.weight, this.time);

  // convert Json to an exercise object
  factory Set.fromJson(Map<String, dynamic> json) {
    return Set(
      json['repetitions'] as int,
      json['weight'] as int,
      json['time'] as int,
    );
  }
}

Error enter image description here

1 Answer 1

2

Your code perfectly works for me.

We will get this error if we miss toList() in below snippet,

(json['sets'] as List).map((i) {
    return Set.fromJson(i);
  }).toList(), // removing toList will get below error
// type 'MappedListIterable<Map<String, int>, Set>' is not a subtype of type 'List<Set>'
Sign up to request clarification or add additional context in comments.

4 Comments

What version of flutter do you use? I use 0.5.1
Same as yours. Dart VM version: 1.24.3
Before this line class Set {, } is missing in above code (looks Set as inner class). As Dart doesn't allow inner class, it should be typo
Sorry, I will change code. The model looks so . gist.github.com/aBuder/ca09a5d08ede710e032f26dbaf45560a

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.