Our topic is the management of Ephemeral state.

Widgets in Flutter are categorized into two categories:

Stateless widgets Stateful widgets

The simple difference between the two, is that the data (State) that is used in creating the Stateful widget can change. Data in a Stateless widget can’t.

Example of stateless widget:

class StatelessButton extends StatelessWidget { @override Widget build(BuildContext context) { return Text("HI!"); } }

we notice that nothing is really changing inside the Widget object, and if we try to define variables inside the class

String _name = “Adnan”;

Flutter would warn us that

This class (or a class which this class inherits from) is marked as ‘@immutable’, but one or more of its instance fields are not final

which means, that the variable we defined is useless, as it won’t contribute to the future state of the widget.

Stateful widgets, on the other hand, can have variables that could contribute in the future state of the widget.

A little extra thing that helps with this process, is the State class.

You might wonder why StatefulWidget and State are separate objects. In Flutter, these two types of objects have different life cycles.

Widgets are temporary objects, used to construct a presentation of the application in its current state.

State objects, on the other hand, are persistent between calls to build(), allowing them to remember information

the build method, calls a method ( setState() ) that inside we do the modifications on the state variables.

after the setState method is executed, the Widget object is replaced with a new one having the modified variable values.

class HomePageState extends State<HomePage> { String _name = "Celil"; @override Widget build(BuildContext context) { return RaisedButton( child: Text(_name), onPressed: () { setState(() { _name = _name == "Celil" ? "Jhon" : "Celil"; }); }, ); } } class HomePage extends StatefulWidget { @override HomePageState createState() { return HomePageState(); } }

we notice that widget object now, returns its corresponding state object.

when the RaisedButton is pressed, setState is triggered and run which changes the _name variable. This variable is then used to create a new updated widget object.

section summary:

Widget Manages its state: