10

Where should one keep final values?

In the StatefulWidget (my subclass of course) instance and access it from the State (subclass) via widget.thatFinalField, or

In the State itself. I've seen both approaches already.. Any pros and cons for each of them?

DogeLion
  • 3,371
  • 5
  • 16
  • 24

1 Answers1

14

You should store final member fields (which are passed via constructor arguments) on the StatefulWidget and make them public.

The StatefulWidget's associated State should use only the default constructor (no arguments), and its member fields should be private (starting with a _) and mutable. Initialize them inline or in initState if expensive or async work is necessary.

This pattern allows the StatefulWidget to be recreated/rebuilt with new constructor arguments when its parents call setState, while re-using the previous State and letting it keep the values stored in its mutable member fields.

Collin Jackson
  • 110,240
  • 31
  • 221
  • 152
  • What about final stream subscriptions? Obtained from services or injector classes. – DogeLion May 09 '17 at 17:19
  • Constructing your StatefulWidget and its associated State should not have any side effects. If you're doing any work that has side effects to initialize your widget, you should be doing it in initState() and saving it to mutable member variables. Make sure to clean up after yourself in dispose(). – Collin Jackson May 09 '17 at 17:22