Extension Methods:
In this blog, we will check the use of Dart Extension methods in the flutter. Extension methods were introduced in Dart 2.7.
Sometimes we need additional functionalities which do not provide in existing libraries. We can add our own functionality by using the extension in the existing class of libraries’ APIs
Extension methods used to add additional functionality to existing libraries’ APIs. We can define extension with methods, getters, setters, and operators.
Read more about Flutter app development.
Extension Syntax:
1 2 3 |
extension <extension name> on <type> { (<member definition>)* } |
Extension On String Class:
Let’s check some String Class extension examples.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
extension StringExtension on String { bool get isNullOrEmpty { return this == null || this.isEmpty; } bool get isNotNullOrEmpty { return !(this == null || this.isEmpty); } get firstLetterToUpperCase { if (this != null) return this[0].toUpperCase() + this.substring(1); else return null; } get removeAllHtmlTags { if (this != null) { RegExp exp = RegExp(r"<[^>]*>", multiLine: true, caseSensitive: true); return this.replaceAll(exp, ''); } else return null; } } |
Extension On List Class:
Let’s check some List Class extension examples.
1 2 3 4 5 |
extension ListExtension on List { bool get isNullOrEmpty { return this == null || this.isEmpty; } } |
Using Extension methods:
You need to just import your extensions methods class and call Extention getter using dot(.) on variable
1 2 3 4 5 |
///Let's remove HTML tags from String String withoutHtmlTags = "String Contains Html Tags".removeAllHtmlTags; String fistLetterWithUpperCase = "String with lower case".firstLetterToUpperCase; |
I hope this blog will help to add some utility functionality to existing APIs.
Happy Learning 🙂
Reference Links:https://dart.dev/guides/language/extension-methods