Null aware in dart list element

Viewed 1460

I was working on a project and wanted to check if a list element was null. Example

List<int> i = [1, 2, 3];
print(i[1]); // this prints 2

But what if I want to print out a list element and if it does not exist print out a default number using dart null-aware. Example

List<int> i = [1, 2, 3];
print(i[10] ?? 15);
// Also tried
print(i?.elementAt(10) ?? 15);

I want it to print out 15 since the element at index 10 does not exist. Unfortunately, the above code gives me an error.

How can I check if a list element does not exist and return a default value

2 Answers

There's no elegant way of doing it, as you are trying to. You will have to check the list length first, because in the moment that the program evaluates i.elementAt(10) it inmediately throws the RangeError exception.

Example solution 1:

if (i.length > 9) { 
    print(i?.elementAt(10));
} else {
    print(15);
}

Example solution 2 (a more elegant way):

print(i.length > 9 ? i?.elementAt(10) : 15);

One solution to have this kind of functionality is to wrap your list with a custom class that catches the inner exception and returns null instead.

I wrote this wrapper bellow and called it XList:

class XList<E> {
  List<E> list;
  XList(this.list);
  E operator [](int position) {
    try {
      return list[position];
    } catch(IndexOutOfBoundException) {
      return null;
    }
  }
}

Now your code works like this:

final list = [1, 2, 3];
final a = XList(list);
print(a[10] ?? 15);
// prints 15
Related