In this blog, I would like to share the amazing concept of Dart Extensions and how to make custom extensions for quality and optimised code.
The specialty of this blog is that it will show you how to create extensions from your JSON models and it is very useful for state management.
Extension is used to enhance the feature of an existing class or a library. Using the extensions, one cannot change the existing properties of the class but can definitely change the view of class or model.
Extensions are identical to the “prototype” of Javascript but unlike executing at the run time, this gets executed at the compile time.
extension <extension name> on <type> {(<member definition>)*}
You can also make this for different data types. Like the below:
extension <extension name> on <class you want to add functionality to, ex: String, Integer, Widget etc>{}
– This is used to convert any type of variable into String.
Ex. double number = 2.0 // variable with type double.
number.toString() // it is converted to a string.
int number = 2 // variable with type int.
number.toString() // it is converted to a string.
– This is used to check how many members are present in a list.
Ex. List<int> numberList = [1, 0, 7, 4, 78]
int numberOfElement = numberList.length
print(numberOfElement)
Answer will be “5”;
<your_date>.toDateFormat(incomingDateFormat: “dd/MM/yyyy HH:mm:ss” , requiredFormat: “yyyy-MM-dd HH:mm:ss”)
The above example gives you a date in your desired format. It’s quite easy but more useful.
Here “LazyLoadModel” is our JSON model. Let me show you an actual model.
In the example above, we converted our entire model into just 1 URL and when you want to use that URL you just have to type the following line.
// variable initialization
LazyLoadModel lazyLoadModel = LazyLoadModel(limit: 0, offset: 1, searchText: “sample”);
Print(lazyLoadModel.getLaztLoadUrl) //
Here “getLaztLoadUrl” is our custom extension which we made above.
Output : “offset=1&limit=5&search=sample”
But using the extension, you can see that the code becomes easier to understand.
In this blog, we have discussed how to create an extension that is not present in Dart built-in but you really need it to optimize your code.
Happy Coding!