Home > Blockchain >  How to fix: value of type 'Map<String, dynamic>', but got one of type 'List<
How to fix: value of type 'Map<String, dynamic>', but got one of type 'List<

Time:06-11

I am trying to pull data from a local restful API. I have already successfully did it with a single data collection. Now I am trying a list and I am running into this issue.

Error: Expected a value of type 'Map<String, dynamic>', but got one of type 'List<dynamic>'

How do I fix this issue?

Code:

JSON MODEL

import 'dart:convert';

List<ProjectJson> welcomeFromJson(String str) => List<ProjectJson>.from(
    json.decode(str).map((x) => ProjectJson.fromJson(x)));

String welcomeToJson(List<ProjectJson> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class ProjectJson {
  ProjectJson({
    required this.job,
    this.description,
    this.deliverTo,
    this.promisedDate,
  });

  String job;
  String? description;
  String? deliverTo;
  DateTime? promisedDate;

  factory ProjectJson.fromJson(Map<String, dynamic> json) => ProjectJson(
        job: json["job"],
        description: json["description"] == null ? null : json["description"],
        deliverTo: json["deliver_To"],
        promisedDate: DateTime.parse(json["promised_Date"]),
      );

  Map<String, dynamic> toJson() => {
        "job": job,
        "description": description == null ? null : description,
        "deliver_To": deliverTo,
        "promised_Date": promisedDate?.toIso8601String(),
      };
}

API CONNECTION

Future<List<ProjectJson>?> OpenProjectCall(
    String CustomerID, String APIKey) async {
  var headers = {'customer_id': CustomerID, 'APIKey': APIKey};
  var request = http.Request(
      'GET',
      Uri.parse(
          'http://65.254.144.50:5114/Customers/{customer_id}/OpenProjects'));

  request.headers.addAll(headers);

  final response = await request.send();
  final String respStr = await response.stream.bytesToString();

  if (response.statusCode == 200) {
    List<ProjectJson> _project = ProjectJson.fromJson(
            jsonDecode(respStr.toString()) as Map<String, dynamic>)
        as List<ProjectJson>;
    print(_project);
  } else {
    print(response.reasonPhrase);
  }
}

I have tried changing the as Map<String, dynamic> to a Map <,dynamic> and Map <dynamic, dynamic> and neither worked. I did change it through out both the API call and Model when testing.

EXPECTED RETURN

[
    {
        "job": "148241",
        "description": null,
        "deliver_To": "KDC One Northern Labs\t",
        "promised_Date": "2022-07-15T00:00:00"
    },
    {
        "job": "148242",
        "description": "With PD, SM And SW",
        "deliver_To": "KDC One Northern Labs\t",
        "promised_Date": "2022-07-15T00:00:00"
    }
]

CodePudding user response:

change

Map<String, dynamic> 

to

List<dynamic>

CodePudding user response:

Currently the ProjectJson.fromJson constructor expects a Map to be passed in, and you're passing in a List<Map>.

So once you have this String

final String respStr = await response.stream.bytesToString();

You need to convert it to a List to access the Maps inside.

final responseList = json.decode(resStr) as List;

Now you have List<Map> that you need to iterate through and pass each individual Map into the ProjectJson.fromJson constructor.

This is one way using Darts map method.

final projectList = responseList.map((project) => ProjectJson.fromJson(project)).toList(); // projectList is a List<ProjectJson>

Below you see it gives you a properly initialized List<ProjectJson

enter image description here

Return that projectList and you're good to go.

  • Related