Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Dart, what's the difference between 'const' parameter?

Tags:

flutter

dart

padding: const EdgeInsets.all(25.0)
padding: EdgeInsets.all(25.0),

In Dart demo, most of padding or child add const, is there any optimization?

https://docs.flutter.io/flutter/widgets/Padding-class.html

like image 401
Devilsen Avatar asked Oct 24 '18 13:10

Devilsen


1 Answers

Let us consider we have these three lines of code:

1.const EdgeInsets.all(25.0)
2.const EdgeInsets.all(25.0)
3.const EdgeInsets.all(25.0)

1. At first line EdgeInsets class creates a new object and assigns its values for left, top, right, bottom and render the given widget and then it creates a constant object with same value for rendering if it is found in another place.

2. Hey there is already an object with this value, so just render it.

3. Hey there is already an object with this value, so just render it.

Now, let us consider these scenario:

1.EdgeInsets.all(25.0)
2.EdgeInsets.all(25.0)
3.EdgeInsets.all(25.0)

1. At first line, EdgeInsets class creates a new object and assigns its values for left, top, right, bottom and render the given widget.

2. At the second line, EdgeInsets class creates a new object and assigns its values for left, top, right, bottom and render the given widget.

3. At third line, EdgeInsets class creates a new object and assigns its values for left, top, right, bottom and render the given widget.

So, by using const we can reduce the time for recreating the same object every time and using it, instead, we create an object once and then reuse it at every time we need.

like image 195
Mohan Munisifreddy Avatar answered Sep 28 '22 05:09

Mohan Munisifreddy