skip to Main Content

I am not sure why I get the Null check operator used on a null value error. I have used an if condition to check if it is before adding it to the list.

Below the print statement prints the expected data. The issue is on the line where I do the addition to the list inside of the for loop.

Future<List<String>?> fetchContacts(List<String> contacts) async {
    QueryResult result = await _client().query(
      QueryOptions(
        document: gql(_fetchContacts),
        variables: {
          'contacts': contacts,
        },
      ),
    );
    List<String>? contacts;

    if (result.data != null) {
      int status = result.data!['fetchContacts']['status'];
      int resultCount = result.data!['fetchContacts']['users'].length;

      if (status == 200 && resultCount != 0) {
        for (int i = 0; i < resultCount; i++) {
          if (result.data?['fetchContacts']['users'][i]['userPhoneNumber'] !=
              null) {
            contacts!.add(result.data?['fetchContacts']['users'][i]
                ['userPhoneNumber']);
            print(result.data!['fetchContacts']['users'][i]
                ['userPhoneNumber']);
          }
        }
      }
    }
    return contacts;
  }

3

Answers


  1. You never initialize your list.
    Instead of making it nullable, try making it empty instead:

    List<String> contacts = [];
    
    Login or Signup to reply.
  2. In case you want your list to nullable, please use this code

        Future<List<String>?> fetchContacts(List<String> contacts) async {
        QueryResult result = await _client().query(
          QueryOptions(
            document: gql(_fetchContacts),
            variables: {
              'contacts': contacts,
            },
          ),
        );
        List<String>? contacts;
    
        if (result.data != null) {
          contacts=[];
          int status = result.data!['fetchContacts']['status'];
          int resultCount = result.data!['fetchContacts']['users'].length;
    
          if (status == 200 && resultCount != 0) {
            for (int i = 0; i < resultCount; i++) {
              if (result.data?['fetchContacts']['users'][i]['userPhoneNumber'] !=
                  null) {
                contacts!.add(result.data?['fetchContacts']['users'][i]
                    ['userPhoneNumber']);
                print(result.data!['fetchContacts']['users'][i]
                    ['userPhoneNumber']);
              }
            }
          }
        }
        return contacts;
      }
    
    Login or Signup to reply.
  3. The issue as I see in here is you didn’t initialize the contacts list variable. You have mentioned it as a nullable but you didn’t check weather this null or not. Without initializing the variable list you have called the add function. that’s why you got the exception message.

    List? contacts = [];

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search