DEV Community

francesco agati
francesco agati

Posted on

Enhancing List Functionality in Dart with Custom Extensions

Dart, a language known for its flexibility and robust features, allows developers to extend the functionality of existing classes without modifying them. One powerful way to achieve this is through extensions. In this article, we'll explore how to create a custom extension for the List class in Dart to add some useful utility methods.

Introduction to Dart Extensions

Extensions in Dart enable you to add new functionalities to existing libraries. By creating an extension, you can introduce new methods and properties to a class without altering its source code. This is particularly useful when you want to augment the capabilities of widely used classes like List.

Creating the ListUtils Extension

Let's dive into the code for our custom extension ListUtils which adds three handy methods to the List class:

  1. firstOrNull: Returns the first element of the list, or null if the list is empty.
  2. lastOrNull: Returns the last element of the list, or null if the list is empty.
  3. takeLast: Returns the last n elements of the list.

Here's the code for our extension:

extension ListUtils<T> on List<T> {
  T? firstOrNull() {
    return isEmpty ? null : this[0];
  }

  T? lastOrNull() {
    return isEmpty ? null : this[length - 1];
  }

  List<T> takeLast(int n) {
    return skip(length - n).toList();
  }
}
Enter fullscreen mode Exit fullscreen mode

Method Breakdown

firstOrNull

This method returns the first element of the list if it exists; otherwise, it returns null.

T? firstOrNull() {
  return isEmpty ? null : this[0];
}
Enter fullscreen mode Exit fullscreen mode

lastOrNull

Similar to firstOrNull, this method returns the last element of the list or null if the list is empty.

T? lastOrNull() {
  return isEmpty ? null : this[length - 1];
}
Enter fullscreen mode Exit fullscreen mode

takeLast

This method returns the last n elements of the list. It uses the skip method to skip the first length - n elements and then converts the remaining elements to a list.

List<T> takeLast(int n) {
  return skip(length - n).toList();
}
Enter fullscreen mode Exit fullscreen mode

Using the Extension

To see our extension in action, we can use the following example in the main function:

void main() {
  var list = [1, 2, 3];
  print(list.firstOrNull()); // Output: 1
  print(list.lastOrNull());  // Output: 3
  print(list.takeLast(2));   // Output: [2, 3]
}
Enter fullscreen mode Exit fullscreen mode

Explanation

  • list.firstOrNull(): Since the list is not empty, this will return the first element, 1.
  • list.lastOrNull(): This will return the last element, 3.
  • list.takeLast(2): This will return the last two elements of the list, [2, 3].

Conclusion

Extensions in Dart provide a powerful mechanism to enhance the functionality of existing classes in a clean and maintainable way. By creating the ListUtils extension, we have added methods to the List class that can simplify common operations. This approach keeps our codebase clean and reusable.

By understanding and utilizing Dart extensions, you can significantly improve your productivity and code quality. Happy coding!

Image of AssemblyAI tool

Transforming Interviews into Publishable Stories with AssemblyAI

Insightview is a modern web application that streamlines the interview workflow for journalists. By leveraging AssemblyAI's LeMUR and Universal-2 technology, it transforms raw interview recordings into structured, actionable content, dramatically reducing the time from recording to publication.

Key Features:
πŸŽ₯ Audio/video file upload with real-time preview
πŸ—£οΈ Advanced transcription with speaker identification
⭐ Automatic highlight extraction of key moments
✍️ AI-powered article draft generation
πŸ“€ Export interview's subtitles in VTT format

Read full post

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay