Error while Adding JSON data to the list in flutter

86 views Asked by At

Below is the JSON data retrieved successfully from the server in flutter application

{
    "error": "false",
    "notification": [
        {
            "rn": "1",
            "id": "224",
            "company_details": {
                "code": "2",
            }
        },
        {
            "rn": "2",
            "id": "219",
            "company_details": {
                "code": "3",
            }
        },
        {
            "rn": "3",
            "id": "213",
            "company_details": {
                "code": "3",
            }
        },
        {
            "rn": "4",
            "id": "209",
            "company_details": {
                "code": "4",
            }
        },
        {
            "rn": "5",
            "id": "204",
            "company_details": {
                "code": "3",
            }
        },
        {
            "rn": "6",
            "id": "199",
            "company_details": {
                "code": "3",
            }
        },
        {
            "rn": "7",
            "id": "193",
            "company_details": {
                "code": "3",
            }
        }
    ],
}

The code used here is below

List notificationsList;
getnotifications(int page) async {

    Map data = {
      'user_id': “VICKY,
      "page":page.toString()
    };


    var response = await http.post(companyorders, body: data);
    if(response.statusCode == 200) {

      jsonResponse = json.decode(response.body);
      print('Response status: ${response.statusCode}');
      print('Response body: ${response.body}');


      String errorcheck = jsonResponse['error'];




      companyDetail = NotificationModel.fromJson(json.decode(response.body));

      companyDetail = NotificationModel.fromJson(json.decode(response.body));

      print('names of companies');
      print(companyDetail.content);

      List list = jsonResponse['notification'];

      notificationsList.add(list);
     
    }
    
  }

When I tried to add the list to the notificationsList I got the below error

Unhandled Exception: NoSuchMethodError: The method 'add' was called on null. Receiver: null Tried calling: add(Instance(length:7) of '_GrowableList') #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)

I want to add the data retrieved to the notificationsList, how should I do that

1

There are 1 answers

0
Peter Haddad On BEST ANSWER

You need to initialize notificationsList:

List notificationsList = [];

Also since list is an iterable therefore use addAll()