Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between the "const" and "final" in Dart?

If I declare that in Dart : final Color _iconColor = Color.fromARGB(210, 198, 15, 1, Vs Code
display this message :
Prefer const with constant constructors.

So the result is :
final Color _iconColor = const Color.fromARGB(210, 198, 15, 1);. And VsCode is good.

But if my variable _iconColor is already final, why add const inside ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

const and final are not the same.

const means that the value is known at compile time, whereas final means that the variable is immutable after being set.

From Flutter best practices here:

Use const constructors on widgets as much as possible, since they
allow Flutter to short-circuit most of the rebuild work

Using const keyword everytime it’s possible will increase your performances, since Flutter won’t have to re-build const widgets.

In your case, you define your _iconColor as final, which means that you won’t be able to modify it afterwards. And you set it to a const value, known at compile time.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading