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());
        },
      ),

>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

Leave a Reply