Search code examples
fluttervariablesdartfinal

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


I noticed in some of the examples online that classes that extend StatefulWidget have instance variables marked with final. Why is that? I understand what the final keyword does. I do not understand why it is being declared with each instance variable that extends the widget class.


Solution

  • 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.