DEV Community

Cover image for Dart Extensions: Tips and Tricks
Alpha
Alpha

Posted on

Dart Extensions: Tips and Tricks

What are Dart Extensions?

Dart Extensions are a way to add new methods, getters, or setters to existing classes. This feature enables developers to write cleaner and more organized code by avoiding the need to create separate utility classes or modify the original class. It also allows for better code reusability.

The need for Dart Extensions arises from the desire to keep code modular and easy to maintain. When you want to add specific functionality to a class, it's better to use extensions instead of cluttering the class with unrelated methods. This approach enhances code readability and maintainability.

How to Define Dart Extensions

Defining a Dart Extension is straightforward. You create an extension by using the extension keyword, followed by the extension name. Then, you specify the class you want to extend and add the new methods, getters, or setters.

extension ExtensionName on ExtendedType {
  // Define extension methods and properties here
}
Enter fullscreen mode Exit fullscreen mode

ExtensionName: This is the name you give to your extension. It can be any valid identifier.

ExtendedType: This is the type you want to extend with additional methods or properties. It can be a class, interface, or a built-in type.

Using Dart Extensions

To use Dart Extensions, import the necessary library and call the extension method on an instance of the class you want to extend. This allows you to access the new functionality provided by the extension.
Extensions can also be used on custom classes as shown in an example below.

Examples

Here's a simple example showing how to extend the dart String class

//defining the extension
extension StringExtension on String {
//getter
  int get wordCount {
    // Split the string by whitespace and count the words
    return split(' ').where((word) => word.isNotEmpty).length;
  }
}

//using the extension
String foo = 'Hello';
print(foo.wordCount); //result: 1

String bar = "My name is Alpha";
print(bar.wordCount); // result: 4

Enter fullscreen mode Exit fullscreen mode

Below is another example extending the integer built-in type

//defining the extension
extension IntExtension on int{
  //method
  bool isPrime(){
    bool prime = true;
    for(int i in List.generate(this, (index) => index+1) ){
      if(i == this) break;
      if(i == 1) continue;
      if(this%i == 0){
        prime = false;
        break;
      } else {
        prime = true;
      }

    }
    return prime;
  }

//using the extension
int x = 2;
print(x.isPrime()); //result: true

print(6.isPrime()); //result: false
print(7.isPrime()); //result: true
print(1101.isPrime()); // result false
}
Enter fullscreen mode Exit fullscreen mode

Notice how we didn't include the brackets when calling the wordCount String extension because it's a getter but we included the brackets in the isPrime() int extension because it is a method(function).

For custom classes:

//class creation
class Person {
  final String name;
  final DateTime birthdate;

  Person({required this.name, required this.birthdate});
}

//extending class
extension PersonAgeExtension on Person {
  int get age {
    final currentDate = DateTime.now();
    final age = currentDate.year - birthdate.year;

    if (birthdate.isAfter(currentDate.subtract(Duration(years: age))) {
      return age - 1;
    } else {
      return age;
    }
  }
}

//using extension
  final person = Person(name: 'John Doe', birthdate: DateTime(1990, 5, 15));

  final age = person.age;
  print('${person.name} is $age years old.');
//result: John doe is 33 years old
Enter fullscreen mode Exit fullscreen mode

Dart Extensions vs. Inheritance

Dart Extensions offers a different approach to extending class functionality compared to inheritance. While inheritance creates a new class hierarchy, extensions enhance existing classes, making them more suitable for certain scenarios.

Compatibility

Dart Extensions are supported in Dart 2.7 and later versions. They work seamlessly with Dart and Flutter, making them an essential feature for developers working on these platforms.

In the context of Flutter, Dart Extensions can be particularly useful for adding custom functionality to Flutter widgets or enhancing the functionality of existing packages. They contribute to creating a more expressive and efficient codebase for Flutter apps.

Conclusion

Dart Extensions are a powerful feature in the Dart programming language, enabling developers to enhance existing classes with new methods and functionality. They improve code organization, reusability, and compatibility, making them a valuable tool in your development arsenal.

Top comments (0)