Extension methods in Dart

Extension methods in Dart

Range Error Handling.

Table of contents

No heading

No headings in the article.

Let's consider a dynamic list with few elements.

List myList = ["mango", "apple", "guava"];

Let's consider you need to print the item at a specific index. For that index, we could do:

carbon (1).png

It simply prints mango in the console.

Now, Let's consider there existed a scenario when you need to print the item at any index including the index that might not be available in the list.

carbon (2).png

In the above list, item doesn't exist at index 3, so if we print item at index 3, we should get null in the console as there exists nothing at myList[3].


Uncaught Error: RangeError (index): Index out of range: index should be less than 3: 3. This error appeared in the console as we tried to access the item at index which doesn't exist. This means that we couldn't access the index that doesn't exist expecting it to print null in console. What if we want to print null if the item at index doesn't exist ?

We could do this:

carbon (3).png

This code works perfectly fine. What if we want to reuse this code ? It isn't a good idea to hard-code this piece of code everywhere. What we could do is create a function that returns item if it exists or null.

carbon (4).png

Nice, The program is running as we expected it to. Let's assume, We need to do this multiple times with multiple lists. In the above piece of code, We passed the index and the list to the function to do the operation but should we be passing the list everywhere ? What if we don't want to pass the list ?

That's where extension method comes in. According to extension method definition in Dart documentation, Extension methods, introduced in Dart 2.7, are a way to add functionality to existing libraries. They can be defined as:

carbon (7).png

Here, we need to add functionality to the list i.e. we need to print item at index or null. Since List is of type Iterable, we can create an extension on Iterables.

carbon (5).png

Now, the question "How to implement this ?" arises. Well, It's easy.

carbon (6).png

After clicking dot after a specific list, The suggestion of itemAtIndexOrNull automatically shows up and we pass the required index and we're done.

The complete source code is:

extension ItemAtIndexOrNull<T> on Iterable<T> {
itemAtIndexOrNull(int index) {
  if (length >= index + 1) {
   return elementAt(index);
  } else {
   return null;