Dart Extensions Part 2: Extensions for Collections

Dart Extensions Part 2: Extensions for Collections

While Part 1 is an introduction to Dart Extensions. This article focuses on improving the quality of the extensions.

Tutorial 4: Extensions for Collections

In here we are going to cover the following topics:

  • Working with collections (List, Map, Set)

  • Adding utility methods for collections

  • Examples of useful collection extensions

Example: Working with Collections

Let's focus on the Map collection. We will create an extension to add a method invert that swaps the keys and values of the map.

extension MapExtensions<K, V> on Map<K, V> {
  Map<V, K> invert() {
    return this.map((key, value) => MapEntry(value, key));
  }
}

void main() {
  Map<String, int> original = {'a': 1, 'b': 2, 'c': 3};

  Map<int, String> inverted = original.invert();

  print(inverted);
}

We did the following things here:

  • The MapExtensions extension adds an invert method to the Map class.

  • The invert method uses the map function to create a new map with the keys and values swapped.

You can find the source code here: Tutorial 3 Collection Extensions

Assignment 4:

Write an extension on the Set class to add a method unionAll that takes a list of sets and returns the union of all sets including the original one.

Solution: Assignment 4 Set Extensions Solution

Tutorial 5: Advanced Extensions and Best Practices

In here we are going to cover following topics:

  • Advanced use cases of extensions

  • Combining extensions with other Dart features

  • Best practices and performance considerations

Advanced Use Cases of Extensions

In this tutorial, we'll explore some advanced use cases of extensions and how to combine them with other Dart features for more powerful and flexible code.

Example: Extending DateTime

Let's create an extension on the DateTime class to add two methods

  • isWeekend that checks if a date falls on a weekend.

  • daysUntil that returns the number of days until another date.

extension DatetimeExtensions on DateTime {
  bool isWeekend() {
    return this.weekday == DateTime.saturday || this.weekday == DateTime.sunday;
  }

  int daysUntil(DateTime other) {
    return other.difference(this).inDays;
  }
}

void main() {
  DateTime today = DateTime.now();
  DateTime futureDate = today.add(Duration(days: 10));

  print('Is today a Weekend? ${today.isWeekend()}');

  print('Days until $futureDate: ${today.daysUntil(futureDate)}');
}

The DateTimeExtensions extension adds two methods to the DateTime class:

  • isWeekend: Checks if the DateTime instance falls on a Saturday or Sunday.

  • daysUntil: Calculates the number of days between the DateTime instance and another date.

Source Code: Tutorial 5 Advanced Extensions

Best Practices

  1. Name Extensions Clearly: Use clear and descriptive names for your extensions to avoid conflicts and improve readability.

  2. Keep Extensions Focused: Extensions should add related functionality and not become a dumping ground for unrelated methods.

  3. Avoid Overusing Extensions: Use extensions judiciously. Overusing them can lead to confusing and hard-to-maintain code.

  4. Document Extensions: Provide comments and documentation for your extensions, especially if they add complex functionality.

Assignment 5:

Create an extension on the List class to add a method average that calculates the average of a list of numbers. Also, add a method median to find the median value of the list.

Solution: Assignment 5 Solution

This concludes our series on Dart extensions. Happy coding!

Did you find this article valuable?

Support Harish Kunchala by becoming a sponsor. Any amount is appreciated!