Reputation: 1901
I've been trying to leverage const
constructors more in my Flutter app lately and I'm curious how deep I need to include the const
keyword. Take the following:
const Text('foo', style: const TextStyle(fontSize: 12));
I know I can make the Text
widget a const because it's a static string. I can also make the TextStyle
a const. But do I need to even include const
on the TextStyle
if its parent Text
is also a const
?
Additionally, if it is the case that I do not need to put a const
inside a const
and change it to the example below, will the second TextStyle
be the same instance as the first?
const Text('foo', style: TextStyle(fontSize: 12));
/// is this TextStyle the same instance as above?
Text(foo.bar, style: const TextStyle(fontSize: 12));
I'd really appreciate any input on this. I struggle to know if I should be littering the codebase with const
or if it's a waste of my time. Thanks in advance!
Upvotes: 1
Views: 154
Reputation: 90155
const
specifies that an object can be initialized at build time. Therefore, const T(x)
requires that x
be known at build time, which means that it also must be const
. Therefore, for const T(U())
, adding a const
qualifier when constructing U
is unnecessary; it's inferred from the context.
If U
is not const
-constructible, then you'll get a build-time error.
Upvotes: 3
Reputation: 8393
There is no need to do littering the codebase with const
.
These are equivalent:
BAD
final b = const [const A()];
GOOD
final b = const [A()];
If you use Lint in your project, the following rule will be useful to detect unnecessary const keywords: unnecessary_const
Don't struggle with these, let Lint tell you what to do.
Upvotes: 4