Mobile App Development — Level 2: Building Real Flutter Apps
Free preview

Stateful widgets and the widget life cycle

1 / 3

State

  • Data that changes over time
  • Stateless vs Stateful
  • UI = f(state)
2 / 3

setState

  • Mark widget dirty
  • Rebuild with new values
  • Keep it local
3 / 3

Life cycle

  • initState
  • build
  • dispose

Lecture notes

In Flutter, the UI is a function of state: when data changes, Flutter rebuilds the widgets that depend on it.

Stateless vs stateful

  • StatelessWidget — depends only on its constructor parameters (a title, an icon).
  • StatefulWidget — owns a State object holding data that changes (a counter, a checkbox, a list loaded from the internet).
class Counter extends StatefulWidget {
  const Counter({super.key});
  @override
  State<Counter> createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int _count = 0;

  void _increment() {
    setState(() {
      _count++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(children: [
      Text('Count: $_count', style: Theme.of(context).textTheme.headlineMedium),
      FilledButton(onPressed: _increment, child: const Text('Add')),
    ]);
  }
}

setState

setState tells Flutter the state changed and schedules a rebuild. Change the data inside the callback. Calling it after the widget is removed causes an error — check mounted after asynchronous work.

Life-cycle methods

  • initState() — called once when the state is created: initialise controllers, start loading data.
  • build() — called on every rebuild; must be fast and free of side effects.
  • didUpdateWidget() — the parent rebuilt with new parameters.
  • dispose() — called when removed: dispose controllers, cancel timers and subscriptions to avoid memory leaks.

Lifting state up

When two widgets need the same data, move the state to their closest common parent and pass values and callbacks down. When this becomes painful (many levels), use a state-management solution such as Provider.

Want to go further?
18 h · Enroll to access every lesson and earn the certificate.
Get Started Free