Without going into details and wild theories that few will read, you are directing the question to Dart, and I will direct it specifically to Flutter (which is Dart’s main use today).
When we access the SDK, we will witness several uses of constructors const among the Widgets, mainly the StatelessWidget
s, in fact, if we create a StatelessWidget
with attributes final
and ask the IDE to create a constructor:
It will automatically create a constructor const
:
And paraphrasing the dart documentation:
CONSIDER making your constructor const if the class Supports it.
If you have a class Where all the Fields are final, and the constructor does Nothing but initialize them, you can make that constructor const. That Lets users create instances of your class in Places Where constants are required-Inside other Larger constants, switch cases, default Parameter values, etc.
In addition to being a good practice, Flutter benefits greatly from this for its performance. That’s because a Statelesswidget built through a builder const
can be reused in the Widgets tree, because this created object is canonicalized, which means that no matter how many times this constant value is called in the code, there will always be only one object in memory. For example this code where we create 2 List objects with const
in Dart, see here in practice:
main() {
var a = const [1,2,3];
var b = const [1,2,3];
print('A e B são os mesmos objetos? ${identical(a, b)}');
}
What in Flutter happens a lot in cases of addition of padding with the famous const EdgeInsets.all(8.0)
. Imagine adding the same padding value to various places in the Widgets tree.
Another issue is that since this object is immutable, its values are final
and it was built with a builder const
, when rebuilding the Widgets tree, these Widgets const
that obviously have not been changed, do not need to be reconstructed, taking place an optimization in the use of setState()
.
Good answer, please repeat the answer to this question: https://answall.com/questions/403700/como-o-uso-de-constructors-cons-pode-best_a-performance-no-flutter @Julio-Henrique-Bitencourt
– rubStackOverflow