[FIXED] How do immutable flutter widgets store their mutable states?

Issue

Warning: Prefer const with constant constructors

cause: – Text("dd")
solution: – const Text("dd")

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.

Sources:
https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html
https://stackoverflow.com/a/58136993/462608

Please give examples to show how do widgets store their mutable states by createState method or in objects to which that State subscribes.

Example:
Which field here is considered mutable?

class CategoryScreen extends StatefulWidget {
  String productId;

  CategoryScreen(this.productId);

  @override
  CategoryScreenState createState() => CategoryScreenState();
}

class CategoryScreenState extends State<CategoryScreen> {
  List<Item> _data = [];

  CategoryController controller = Get.put(CategoryController());

  setState(() {
     controller.selectedCategoryIndex.value = panelIndex;
  });
}

Solution

Generally you want the fields in your StatefulWidget object to be final so instead of String productId write final String productId. You can reference those fields from the State object using the widget property, e.g. widget.productId.

Fields in the State object can be mutable, and in your example both _data and controller are technically mutable.

Typically you would initialize that data in initState, so you might for instance use the controller to fill the _data list using an API call, then call setState to trigger the build of the widget. That’s what makes this widget ‘Stateful’.

Stateless widget don’t hold mutable state (e.g. the Text widget has no mutable state, just the text you create it with and it won’t change).
Note that Stateless does not mean that a widget cannot change. For example, a stateless widget can listen to a data stream and adjust its representation accordingly – but it won’t hold state.

Answered By – Bram

Answer Checked By – Clifford M. (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published