Jama Mohamed
Jama Mohamed

Reputation: 3405

Null aware in dart list element

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

Upvotes: 5

Views: 2223

Answers (3)

Zimes
Zimes

Reputation: 623

You can create an extension on Iterable to easily have a method that returns null if the provided index is out of bounds:

extension SafeAccess<T> on Iterable<T> {
  T? safeElementAt(int index) => this.length <= index ? null : this.elementAt(index);
}

you can put this in a general-purpose file like lib/extensions/iterable_extensions.dart in your codebase and then import it whenever you need it.

Upvotes: 0

Dusk
Dusk

Reputation: 1877

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

Upvotes: 4

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);

Upvotes: 3

Related Questions