When you build an app in Flutter, it goes through different states depending on how the user interacts with it (open, minimize, back button, etc).
Think of it like a human day cycle – Wake up → Active → Sleep → Wake again.
🌱 1. main()
– Birth of the App
Every Flutter app starts from the main()
function.
void main() { runApp(MyApp()); }
👉 This is like turning ON the lights – your app is born.
🏗 2. Widgets Lifecycle
In Flutter, everything is a Widget.
There are two main types:
-
StatelessWidget → UI that doesn’t change.
-
StatefulWidget → UI that changes with user interaction.
For StatefulWidget, the lifecycle looks like this:
🔹 When Widget is created
-
createState()
→ Creates aState
object (like preparing memory). -
initState()
→ First time setup (like waking up, stretching, preparing breakfast).-
Best place for API calls, animation controllers, initial values.
-
🔹 When Widget builds
-
build()
→ Renders UI (like dressing up for the day).-
Called multiple times whenever
setState()
is triggered.
-
🔹 When Widget updates
-
didUpdateWidget()
→ Called when parent widget changes (like when your boss gives new instructions but you’re the same person).
🔹 When Widget is removed
-
dispose()
→ Cleanup (like going to sleep, turning off lights).-
Best place to close streams, dispose controllers.
-
📱 3. App Lifecycle (whole app, not just widget)
Flutter gives AppLifecycleState inside WidgetsBindingObserver
.
The states are:
-
resumed
→ App is in foreground (visible, active). -
inactive
→ App is in foreground but not interactive (e.g. phone call overlay). -
paused
→ App is in background (user minimized or switched apps). -
detached
→ App is about to be killed (rare on Android, more common on iOS).
👉 Example:
class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> with WidgetsBindingObserver { @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); } @override void didChangeAppLifecycleState(AppLifecycleState state) { print("App state: $state"); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); super.dispose(); } @override Widget build(BuildContext context) { return MaterialApp(home: Scaffold(body: Center(child: Text("Lifecycle Demo")))); } }
🧠 Easy Analogy
-
initState() → Wake up, get ready.
-
build() → Show yourself to the world.
-
setState() → Change clothes/mood anytime.
-
dispose() → Go to bed.
-
AppLifecycleState.paused → You’re on a tea break.
-
AppLifecycleState.resumed → Back to work.
Comments
Post a Comment