0

I want to load some data from my API.

I build the model for the data I want to receive like this:

  int? id;
  int? createdAt;
  int? eventsId;
  int? userId;
  String? deleteindex;
  int? pferdeId;
  Vertreter? vVertreter;

  VertreterModell(
      {this.id,
      this.createdAt,
      this.eventsId,
      this.userId,
      this.deleteindex,
      this.pferdeId,
      this.vVertreter});

  VertreterModell.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    createdAt = json['created_at'];
    eventsId = json['events_id'];
    userId = json['user_id'];
    deleteindex = json['deleteindex'];
    pferdeId = json['pferde_id'];
    vVertreter = json['_vertreter'] != null
        ? new Vertreter.fromJson(json['_vertreter'])
        : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['created_at'] = this.createdAt;
    data['events_id'] = this.eventsId;
    data['user_id'] = this.userId;
    data['deleteindex'] = this.deleteindex;
    data['pferde_id'] = this.pferdeId;
    if (this.vVertreter != null) {
      data['_vertreter'] = this.vVertreter!.toJson();
    }
    return data;
  }
}

class Vertreter {
  String? name;
  Profilbild? profilbild;

  Vertreter({this.name, this.profilbild});

  Vertreter.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    profilbild = json['profilbild'] != null
        ? new Profilbild.fromJson(json['profilbild'])
        : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    if (this.profilbild != null) {
      data['profilbild'] = this.profilbild!.toJson();
    }
    return data;
  }
}

class Profilbild {
  String? url;

  Profilbild({this.url});

  Profilbild.fromJson(Map<String, dynamic> json) {
    url = json['url'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['url'] = this.url;
    return data;
  }
}

and my API Code looks like this:

    const storage = FlutterSecureStorage();
    var token = await storage.read(key: "_authToken");
    var url = Uri.parse('${Constants.BASE_URL}/vertretung/vertreter');

    var headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer $token',
    };

    var res = await http.get(url, headers: headers);
    final result = json.decode(res.body);
    print(result);
    return result.map<VertreterModell>(VertreterModell.fromJson).toList();
  }

Every time I call the API i get an error:

type '(Map<String, dynamic>) => VertreterModell' is not a subtype of type '(dynamic) => VertreterModell' of 'f'

Any ideas what I am doing wrong? It works for other api functions I made. Thanks in advance!

2 Answers 2

1

result has runtime type List<dynamic>, so it can't be mapped using a function that takes Map<String, dynamic> parameter.

Also since result has type dynamic but has runtime type of List<dynamic>, you can still use map, but there is no static analysis about the usage of it.

You can try

result.map<VertreterModell>((data) => VertreterModell.fromJson(data) ).toList();

Since data have type dynamic here.

    final oldList = jsonDecode('[{"a": "1"},{"b": "2"},{"c": "3"}]');
    print(oldList.runtimeType); // List<dynamic>

    //runtime error, but no static analysis error
    oldList.map<MyClass>(MyClass.fromJson).toList();

    //static analysis error
    (oldList as List<dynamic>).map<MyClass>(MyClass.fromJson).toList();

    //no error
    final newList = oldList.map<MyClass>((data) => MyClass.fromJson(data)).toList();
    print(newList);
Sign up to request clarification or add additional context in comments.

Comments

1

Once try to create model using this tool. https://ashamp.github.io/jsonToDartModel/

And use this method for api calling

const storage = FlutterSecureStorage();
    var token = await storage.read(key: "_authToken");
    var url = Uri.parse('${Constants.BASE_URL}/vertretung/vertreter');

    var headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer $token',
    };

    var res = await http.get(url, headers: headers);
    final result = json.decode(res.body);
    print(result);
    YourModel yourModelName = YourModel.fromJson(result);
    ///return if you want data usign **yourModelName** object.
    return yourModelName;
  }

I Hope this things are solve your issue.

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.