What's with the final/const craze in Flutter?
const
means that the value of the variable is known at compile time and it is going to be constant for the whole duration of the application.
Since the value is known at compile time, you can make the necessary optimisations.
final
means that the value will be constant or immutable from the moment it is set. But it is set at runtime. So you don't know it at compile time and you can't optimise it.
If you don't use final
you lose the immutability feature to what you should adhere in Flutter. You should always create a widget, not modify it. And the way to enforce that is to make all its fields final.
All these finals are not here just for fun. Flutter revolves around immutability. final
is a neat way to enforce that immutability, ensuring you are correctly following the different design patterns.
They are definitely not "excess of correctness" no. They exists to assure a maintainable app. 2 characters is absolutely worth the effort
The main upside of using const
is that, in a reactive UI like Flutter where large parts of the widget tree may be rebuilt regularly, every single object (and all of its own variables) of every single widget will need to be recreated on every rebuild, except if they are marked const
, in which case the same instance will be reused throughout the lifetime of the app.
Even with a moderately complex UI this will quickly save thousands of object instantiations, which can be significant especially when animating widgets. So, it is considered a good practice to use const
when possible.
final
is different, it doesn't bring any performance benefits and is mainly a way to ensure that you are following Flutter design patterns. In my opinion it improves readability in the way that knowing quickly what is immutable and what is not can be very important when developing with Flutter.