Search code examples
flutterdartflutter-listview

NoSuchMethod Exception in Flutter


I am trying to make a get Api call and fetch all the names from the list and populate in a listview.

Below is an example of my json structure

{
    "code": 100,
    "msg": "Success",
    "data": {
        "groups": [
            {
                "name": "group aa",
                "email": "[email protected]",
                "zipcode": "34543",
                "buildName": "11",
                "platform": "Web",
                "createdDate": "2021-06-18 15:39:56",
                "updatedDate": "2021-06-18 15:39:56",
                "id": "c7f8e7f5-b17f-4083-be43-69a1c1ea852c"
            },
         ],
}

For that I have already created a model class

class Group {
  Group({
    this.name,
    this.email,
    this.zipcode,
    this.buildName,
    this.platform,
    this.createdDate,
    this.updatedDate,
    this.id,
  });

  String name;
  String email;
  String zipcode;
  String buildName;
  String platform;
  DateTime createdDate;
  DateTime updatedDate;
  String id;

  factory Group.fromJson(Map<String, dynamic> json) => Group(
        name: json["name"],
        email: json["email"],
        zipcode: json["zipcode"],
        buildName: json["buildName"],
        platform: json["platform"],
        createdDate: DateTime.parse(json["createdDate"]),
        updatedDate: DateTime.parse(json["updatedDate"]),
        id: json["id"],
      );

  Map<String, dynamic> toJson() => {
        "name": name,
        "email": email,
        "zipcode": zipcode,
        "buildName": buildName,
        "platform": platform,
        "createdDate": createdDate.toIso8601String(),
        "updatedDate": updatedDate.toIso8601String(),
        "id": id,
      };

The issue is, I am doing a get call and filtering data from groups array and just taking names, but getting a Exception as below

NoSuchMethodError: The method 'forEach' was called on null.

Below is the Api Code, also there is response in the api call. checked in postman

void getUserGroups() async {
    http.Response response = await http.get(Uri.parse(
        'Api Url'));
    final Map<String, dynamic> responseData = json.decode(response.body);
    responseData['groups'].forEach((groupDetails) {
      final Group groups = Group(name: groupDetails['name']);
      setState(() {
        items.add(groups);
      });
    });
  }

Not sure where its going wrong, it says forEach is having problems. But not able to understand the issue


Solution

  • You call responseData['groups'], but look at your json, it contains data object above groups. Call responseData['data']['groups']