Open In App

Flutter – What are Extensions and How to Use It?

Last Updated : 14 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Dart/Flutter, an extension is a way to add functionality to an existing class without modifying the class itself. Extensions are defined separately from the class and can be used to provide new methods and properties to a class. To create an extension in Flutter, you first need to define the extension using the extension keyword, followed by the name of the extension and the class it extends.

For Example

Dart




extension MyExtension on String {
  int get lengthSquared => this.length * this.length;
  
  String capitalize() {
    return "${this[0].toUpperCase()}${this.substring(1)}";
  }
}


In the above example we create a MyExtension using the extension keyword that extends the Class String, The extension provides two functionality. First, it’s to the square of the length of the String. Second, it capitalizes the first letter of the word. This keyword is used to reference the given string.

Implementation

Dart




void main() {
  List<int> numbers = [1, 2, 3, 2, 4, 5, 1, 6];
  List<int> uniqueNumbers = numbers.removeDuplicates();
  print(
       // prints[1, 2, 3, 2, 4, 5, 1, 6]
      'Before Removing Duplicates: ${numbers}'); 
  print(
       // prints [1, 2, 3, 4, 5, 6]
      'After Removing Duplicates : ${uniqueNumbers}'); 
}
  
extension ListExtensions<T> on List<T> {
  List<T> removeDuplicates() {
    return [
      ...{...this}.toList()
    ];
  }
}


Output

Before Removing Duplicates: [1, 2, 3, 2, 4, 5, 1, 6]
After Removing Duplicates : [1, 2, 3, 4, 5, 6]

Code Explanation

  • main is a Principal Method called once the Program is Loaded.
  • Then we have a List of type int that contains the duplicate integers.
  • Then we apply the removeDuplicates extension (not defined yet) on the List numbers and assign the result to the new List name uniqueNumbers.
  • In the next two lines, we print both of the Lists.
  • Outside of the main method we create the extension name ListExtension that extends the class List and removes the duplicates from the list.

Explanation of extension:  ListExtension

  • We define an extension called ListExtensions that extends the generic List class. The extension provides a new method called removeDuplicates() that removes any duplicate elements from a list and returns a new list with the unique elements.
  • The removeDuplicates() method first creates a Set from the list using the spread operator (…) and the set literal syntax ({…this}), which removes any duplicate elements. It then converts the set back to a list using the toList() method and returns the new list.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads