Why are certain variables marked as final in flutter custom classes?

Because StatefulWidget inherits Widget, which is marked as @immutable, any subclass of StatefulWidget must also be immutable (i.e. all fields final).

If you make a StatefulWidget subclass with non-final fields, it will result in this Dart analysis warning:

info: This class inherits from a class marked as @immutable, and therefore should be immutable (all instance fields must be final). (must_be_immutable at [...] lib....dart:23)

And an explanation of how to use StatefulWidget from the StatefulWidget documentation:

StatefulWidget instances themselves are immutable and store their mutable state either in separate State objects that are created by the createState method, or in objects to which that State subscribes, for example Stream or ChangeNotifier objects, to which references are stored in final fields on the StatefulWidget itself.


There's no finite answer to this question. This is more of a preference.

Fact is that if a variable can be declared as final, then why not declare is as so ? final keyword doesn't hurt your code at all and can potentially help catch bugs.

In fact you can even enable a custom linter rule called prefer_final_locals which will make compilation fails if you have a non-final variable that is never reassigned.

This allows a double health check : immutable variables won't be able to change. But at the same time, if you forgot to mutate a non-final variable, the compiler will also warn you.


"final" is very similar to "const" in application but different for compile-time reasons: See this link or below for further explanation:

"final" means single-assignment: a final variable or field must have an initializer. Once assigned a value, a final variable's value cannot be changed. final modifies variables.

"const" has a meaning that's a bit more complex and subtle in Dart. const modifies values. You can use it when creating collections, like const [1, 2, 3], and when constructing objects (instead of new) like const Point(2, 3). Here, const means that the object's entire deep state can be determined entirely at compile time and that the object will be frozen and completely immutable.