All 7 Flutter Widgets Fundamentals (Stateless & Stateful) questions
More in Flutter Widgets Fundamentals (Stateless & Stateful)
Advertisement
Back to results for “Fundamentals”
Flutter › Flutter Widgets Fundamentals (Stateless & Stateful)

What are the key lifecycle methods of a StatefulWidget's own associated State object, specifically initState, didUpdateWidget, and dispose, and when does each one actually genuinely get called?

Intermediate

Answer

initState is genuinely called exactly one single time when a given State object is first actually properly created, making it the genuinely correct appropriate place to perform any required one time setup work, such as initializing a controller or beginning an initial data fetch, didUpdateWidget is genuinely called whenever the parent widget rebuilds and provides a brand new updated widget configuration to an already existing State object, letting you properly react to any specific meaningful changes in that widget's own received input parameters, and dispose is genuinely called exactly once when that specific State object is being permanently and completely removed from the overall widget tree, making it the genuinely correct appropriate place to properly clean up any resources, such as canceling an active subscription or disposing of a controller.
@override
void initState() {
  super.initState();
  _controller = AnimationController(vsync: this, duration: Duration(seconds: 1));
}

@override
void dispose() {
  _controller.dispose();
  super.dispose();
}
Real-world example A video player widget properly initializes its own VideoPlayerController within initState and correctly disposes of that exact same controller within dispose, correctly and reliably ensuring that valuable underlying native video resource is genuinely properly released the moment that specific widget is actually removed from the screen.

Common follow-ups: What genuinely happens if you forget to actually call super.initState or super.dispose?;What is the specific practical difference between initState and the considerably later called build method?