Widget Lifecycle Events

 In programming, you have different lifecycle events that usually happen in a linear mode, one after another as each stage is completed. In this section, you’ll learn the widget lifecycle events and their purpose.


To build the UI, you use two main types of widgets, StatelessWidget and StatefulWidget. A stateless widget is used when the values (state) do not change, and the stateful widget is used when values (state) change.


The StatelessWidget Lifecycle

A StatelessWidget is built based on its own configuration and does not change dynamically. For example, the screen displays an image with a description and will not change. The stateless widget is declared with one class.

The build (the UI portions) method of the stateless widget can be called from three different scenarios. It can be called the first time the widget is created, when the widget’s parent changes, and when an InheritedWidget has changed.

The following sample code shows a StatelessWidget base structure, and Figure 1.1 displays the widget’s lifecycle

class JournalList extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container();
}
}

 




The StatefulWidget Lifecycle

A StatefulWidget is built based on its own configuration but can change dynamically. For example, the screen displays an icon with a description, but values can change based on the user’s interaction, like choosing a different icon or description. This type of widget has a mutable state that can change over time. The stateful widget is declared with two classes, the StatefulWidget class and the State class.

The StatefulWidget class is rebuilt when the widget’s configuration changes, but the State class can persist (remain), enhancing performance. For example, when the state changes, the widget is rebuilt. If the StatefulWidget is removed from the tree and then inserted back into the tree sometime in the future, a new State object is created. 

You call the setState() method to notify the framework that this object has changes, and the widget’s build method is called (scheduled). You would set the new state values inside the setState() method. 

class JournalEdit extends StatefulWidget {
const JournalEdit({Key? key}) : super(key: key);

@override
State<JournalEdit> createState() => _JournalEditState();
}

class _JournalEditState extends State<JournalEdit> {
@override
Widget build(BuildContext context) {
return Container();
}
}

You can override different portions of the StatefulWidget to customize and manipulate data at different points of the widget lifecycle. Table 1.1 shows some of the stateful widget main overrides, and the majority of the time you’ll use the initState(), didChangeDependencies(), and dispose() methods. You’ll use the build() method all of the time to build your UI.






import 'package:flutter/material.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Widget Lifecycle',
home: const HomeScreen(),
);
}
}

class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});

@override
_HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
bool showWidget = true;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Flutter Widget Lifecycle")),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (showWidget) const LifecycleWidget(),

const SizedBox(height: 20),

ElevatedButton(
onPressed: () {
setState(() {
showWidget = !showWidget;
});
},
child: Text(showWidget ? "Remove Widget" : "Show Widget"),
),
],
),
),
);
}
}

class LifecycleWidget extends StatefulWidget {
const LifecycleWidget({super.key});

@override
_LifecycleWidgetState createState() => _LifecycleWidgetState();
}

class _LifecycleWidgetState extends State<LifecycleWidget> {

/// **1️⃣ initState()** → Widget ka first time creation ke samay call hota hai.
@override
void initState() {
super.initState();
print("initState() called - Widget created");
}

/// **2️⃣ didChangeDependencies()** → Jab inherited widgets ya dependencies change hoti hain, tab call hota hai.
@override
void didChangeDependencies() {
super.didChangeDependencies();
print("didChangeDependencies() called - Dependencies updated");
}

/// **3️⃣ build()** → Jab bhi widget redraw hota hai, tab ye call hota hai.
@override
Widget build(BuildContext context) {
print("build() called - UI is being built");
return Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(10),
),
child: const Text(
"Widget Lifecycle Demo",
style: TextStyle(color: Colors.white, fontSize: 18),
),
);
}

/// **4️⃣ didUpdateWidget()** → Jab widget update hota hai (same state ke sath), tab ye call hota hai.
@override
void didUpdateWidget(covariant LifecycleWidget oldWidget) {
super.didUpdateWidget(oldWidget);
print("didUpdateWidget() called - Widget updated");
}

/// **5️⃣ deactivate()** → Jab widget tree se remove hota hai, tab ye call hota hai.
@override
void deactivate() {
print("deactivate() called - Widget is being removed");
super.deactivate();
}

/// **6️⃣ dispose()** → Jab widget permanently destroy ho jata hai, tab ye call hota hai.
@override
void dispose() {
print("dispose() called - Widget destroyed");
super.dispose();
}
}







Comments

Popular posts from this blog

Unlocking the Power of OOP: A Beginner's Guide to Objects, Encapsulation, Inheritance, Abstraction, and Polymorphism

Flutter Drawer – Create a Smooth Navigation Menu

Mastering Hive in Flutter: A Complete Guide for Beginners to Advanced Users