Home > Blockchain >  Null checking the array in flutter
Null checking the array in flutter

Time:10-07

I'm trying to compare my phone contacts against a list of phone numbers. In my phone contacts, I may have invalid contacts. Here I am trying to null-check the phone array but It throws an error. Do any suggestions pls? Thanks in advance screenshot

CodePudding user response:

Because the simcontact?.phones can be null. So use the ?.elementAt or ?[] rather than the only [] operator.

List<String>? nullableList = null;

final element = nullableList?.elementAt(0);
final element2 = nullableList?[0];

CodePudding user response:

your code...

var tempsearchResult =
    simcontacts.cast().firstWhere((simcontact) => flattenPhoneNumber(simcontact?.phones[0].value) == ...);

modify as...

var tempsearchResult = simcontacts.cast().firstWhere((simcontact) {
  if (simcontact?.phones?.length > 0) {
    return flattenPhoneNumber(simcontact?.phones?[0].value) == 123 /*your comparison value*/;
  }
  return false;
});

CodePudding user response:

The problem is that the list of phones can be empty. Accessing the first element then will throw an error then.

Try writing instead of

simcontact?.phones[0].value

write

simcontact?.phones?.firstOrNull?.value

This will need the following import to use firstOrNull

import 'package:collection/collection.dart';
  • Related