Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter Map inside a Map when fetching from api

Im fetching data from api, but now that im using some other api that has a map inside a map witch im having a problem accessing, here is how the data looks.

{
  "status": "string",
  "name": {
    "location": "string",
    "startTime": "2022-01-31T08:13:21.027Z",
    "endTime": "2022-01-31T08:13:21.027Z",
    "duration": "string"
  }
}

Im trying to access location.

class WorkingLocationStatus {
  final String status;

  //final String location;

  WorkingLocationStatus({
    required this.status,
    // required this.location
  });

  factory WorkingLocationStatus.fromJson(Map<String, dynamic> json) {
    return WorkingLocationStatus(
      status: json['status'],
      //location: json['location']
    );
  }
}

body: FutureBuilder<Response>(
        future: futureDataForStatus,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            WorkingLocationStatus data4 = WorkingLocationStatus.fromJson(
              json.decode(snapshot.data!.body),
            );
            return Center(
              child: Text(data4.status),
            );
          } else if (snapshot.hasError) {
            return Text('${snapshot.error}');
          }
          return const Center(child: CircularProgressIndicator());
        },
      ),

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To access the "location" property you will first need to access it from the field "name":

class WorkingLocationStatus {
  final String status;
  final String location;

  WorkingLocationStatus({
    required this.status,
    required this.location
  });

  factory WorkingLocationStatus.fromJson(Map<String, dynamic> json) {
    return WorkingLocationStatus(
      status: json['status'] as String,
      location: json['name']['location'] as String,
    );
  }
}

Try the full code example on DartPad

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading