Open In App

Flutter – What are Extensions and How to Use It?

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




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




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

Explanation of extension:  ListExtension


Article Tags :