How does Flutter treat state

UI = f(state)

Flutter inserts information to display from the state, so whenever state is changed widgets affected by this state have to be rebuilt.

UI = f(state) Source: https://flutter.dev/docs/development/data-and-backend/state-mgmt/declarative

State in Flutter is stored as fields of State inheritants. Stateful widgets maintain state that might change during the lifetime of the widget. Implementing a stateful widget requires at least two classes: 1) a StatefulWidget class that creates an instance of 2) a State class.

class ExampleStatefulWidget extends StatefulWidget {
@override
_ExampleStatefulWidgetState createState() => _ExampleStatefulWidgetState();
}
class _ExampleStatefulWidgetState extends State<ExampleStatefulWidget> {
@override
Widget build(BuildContext context) {
return Container();
}
}

State is detached from a widget

The StatefulWidget class is, itself, immutable and can be thrown away and regenerated, but the State class persists over the lifetime of the widget.

Change the state with setState(() {})

Flutter takes a function as a parameter that is resposible for state update. Passed in lambda should just update the fields, and will do so in an asynchronous manner.

class ExampleStatefulWidget extends StatefulWidget {
@override
_ExampleStatefulWidgetState createState() => _ExampleStatefulWidgetState();
}
class _ExampleStatefulWidgetState extends State<ExampleStatefulWidget> {
int _counter = 0;
@override
Widget build(BuildContext context) {
return FlatButton(
onPressed: () => setState(() { _counter++; }),
child: Text('Increment'),
);
}
}

Keys makes things clear for Flutter

Key are important for Flutter to recognize which state should be attached to which widget after a rebuild. Each Widget inheritant can pass a Key instance to the parent class:

class ExampleKeyedWidget extends StatefulWidget {
ExampleKeyedWidget({Key key}): super(key: key);
}
tip

There's a great Emily Fortuna's explaination of Keys inner workings here.