initState and dispose
- Flutter course
- Beginner
- Lesson 24/99
- 4 min
Learn the initState and dispose lifecycle methods.
Lifecycle
A State object has a lifecycle. initState is called once when the State is first inserted into the tree; here you set up database connections, listeners or controllers (denetleyici). dispose is called when the State is removed from the tree; here you clean up the resources you created.
class _SayacState extends State<Sayac> {
late TextEditingController denetleyici;
@override
void initState() {
super.initState();
denetleyici = TextEditingController();
}
@override
void dispose() {
denetleyici.dispose();
super.dispose();
}
}Resource cleanup
Every resource opened in initState must be closed in dispose. Otherwise a memory leak occurs. Objects such as TextEditingController, StreamSubscription and AnimationController are closed in the dispose method. super.dispose() must always be called.
@override
void dispose() {
denetleyici.dispose(); // release the controller
dinleyici.cancel(); // cancel the subscription
super.dispose(); // notify the superclass
}Practice Print lifecycle info
In main, print two lines with print: initState baslar and dispose bitir.
Starter code
void main() {
// iki satır yazdır:
// initState baslar
// dispose bitir
}Sample solution
void main() {
print('initState baslar');
print('dispose bitir');
}Expected output
initState baslar dispose bitir
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is initState called?
- Every time setState is called
- Once when the State is first inserted into the tree Correct answer
- Repeatedly every time the app opens
- Before every build
Explanation: initState is called once when the State is first inserted; resource setup is done here.
2 Lifecycle method
@override
void ____() {
super.dispose();
denetleyici.dispose();
}
@override
void dispose() {
super.dispose();
denetleyici.dispose();
}
Explanation: The dispose method cleans up resources when the State is removed from the tree.
3 Lifecycle concepts
| Term | Meaning |
|---|---|
initState |
Called once when State is inserted |
dispose |
Called when State is removed |
lifecycle |
State's start-to-end lifetime |
memory leak |
Happens when a resource is not closed |