Your Second Flutter App, Episode 8: Parse Domains | raywenderlich.com

See how to parse more complicated data returned from the API, a list of domains associated with each course.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/25841733-your-second-flutter-app/lessons/8

When I run the app I get the following:

Exception has occurred.

NoSuchMethodError (NoSuchMethodError: Class 'Domain' has no instance method '[]'. Receiver: Instance of 'Domain' Tried calling: []("id"))

So, I changed the code to:

course.dart

Course.fromJson(Map<String, dynamic> json)
      : courseId = json['id'] as String,
        name = json['attributes']['name'] as String,
        description = json['attributes']['description_plain_text'] as String,
        artworkUrl = json['attributes']['card_artwork_url'] as String,
        difficulty = json['attributes']['difficulty'] as String,
        contributors = json['attributes']['contributor_string'] as String,
        domains = List.from(json['relationships']['domains']['data'])
            .map((e) => Domain.fromJson(Map.from(e)))
            .toList();

Looks like the API response has changed. The type field is always “domains”, so I ended up using the id field to figure out the name.

domain.dart

class Domain {
  final String id;
  final String type;

  Domain(this.id, this.type);

  Domain.fromJson(Map<String, String> json)
      : id = json['id'] as String,
        type = json['type'] as String;

  String get name {
    switch (id) {
      case Constants.iosDomain:
        return Strings.ios;
      case Constants.androidDomain:
        return Strings.android;
      case Constants.flutterDomain:
        return Strings.flutter;
      case Constants.sssDomain:
        return Strings.sss;
      case Constants.unityDomain:
        return Strings.unity;
      case Constants.macosDomain:
        return Strings.macos;
      case Constants.archivedDomain:
        return Strings.archived;
      default:
        return Strings.unknown;
    }
  }
}