When creating a widget tree, will inserting const
before static widgets improve performance?
ie
child: const Text('This is some text');
vs
child: Text('This is some text');
I know that, with Dart 2, const
is optional and will be inserted automatically is some places. Is this one of those situations? If it isn't, will using const
reduce memory usage/improve performance?
Thanks for your answers!
The const keyword is used when the value of the variable is known at compile-time and never changes. In other words, the compiler knows in advance what value is to be stored in that variable.
A const constructor is an optimization! The compiler makes the object immutable, allocating the same portion of memory for all Text('Hi!') objects. But not Text(Math. random()) though, as its value can't be determined at compile time!
A Flutter app is represented by a widget tree, similar to how the DOM on the browser is a tree structure. The widget tree is an actual tree data structure in code built behind the scenes by Flutter, but it's also a useful way to talk about the structure of your Flutter app.
It is a small performance improvement, but it can add up in larger apps or apps where the view is rebuilt often for example because of animations.const
reduces the required work for the Garbage Collector.
You can enable some linter rules in analysis_options.yaml
that tell you when you should add const
because it's not inferred but would be possible like
or that reminds you when you use const
but it is inferred anyway
See also https://www.dartlang.org/guides/language/analysis-options
In the case of Flutter, the real gain with const
is not having less instantiation. Flutter has a special treatment for when the instance of a widget doesn't change: it doesn't rebuild them.
Consider the following:
Foo( child: const Bar( child: Baz() ), )
In the case of build
method being called again (setState
, parent rebuild, Inheritedwidget
...), then due to the const
for Bar
subtree, only Foo
will see its build
method called.
Bar
will never get rebuilt because of its parent, because Flutter knows that since the widget instance didn't change, there's nothing to update.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With