The class StatelessWidget
is marked as immutable
. However, I am using the scoped model
, which means that I avoid StatefulWidget
and use the model
to alter state
in StatelessWidget
. This leads to me having non-final fields
in StatelessWidget
, which doesn't cause errors
, because it's just a warning
. But I wondered if there is a better way?
Flutter: Mutable fields in stateless widgets
6.7k Views Asked by footurist At
2
There are 2 best solutions below
0

Here's you question:
Do you think there is a better approach to accomplish what I want while keeping the "short class structure" that helps me keep oversight and being able to trigger rebuilds of those classes from anywhere?
What you're asking for here ↑ seems to be one more app state management approach that should be better than scoped model.
As you know, app state management approaches are a set of techniques that allow you as a developer:
- to bind data with widgets.
Binding data with widgets, in turn, helps you as a developer:
- to rebuild widgets automatically on every change of bound data.
Maybe, for that purpose, you can make use of rxdart:
Here you will find some very helpful list of app state management approaches that can lead you to a better way of app development:
Stateless widgets should only have final fields, with no exceptions. Reason: When the parent widget is rebuilt for some reason (screen rotation, animations, scrolling...), the
build
method of the parent is called, which causes all widgets to be reconstructed.Classes the extend
StatefulWidget
must follow the same rule, because those are also reconstructed. Only theState
, which can contain mutable fields, is kept during the lifetime of widget in the layout tree.There is no reason to avoid
StatefulWidget
. It is a fundamental building block of Flutter.In fact,
ScopedModelDescendant
is also a stateful widget. The primary benefit of scoped_model is that you can separate the business logic from the widget layer. It doesn't eliminate the need for stateful widgets.Use stateful widgets for:
ScopedModel
widget). Store theModel
instance in theState
.TextEditingController
, state of a checkbox)AnimationController
sController
(TabController
,ScrollController
, ...)It is often a good idea to make the "page" widgets (widgets which build a
Scaffold
, accessible using theNavigator
) stateful. Often these are the hosts for scoped models.