In Flutter, StatefulWidget has dispose()
and deactivate()
. How are they different?

- 2,452
- 1
- 14
- 32
4 Answers
dispose
is definitive. deactivate
is not.
deactivate
is called when a widget may be disposed. But that is not guaranteed.
A typical situation where deactivate
is called but not dispose
,is when moving widgets in the widget tree using a GlobalKey
.

- 256,336
- 79
- 519
- 432
-
Is there a source for this? Thanks – Ben Butterworth Sep 09 '20 at 22:04
-
2@BenButterworth [this is the link for the deactivate method](https://api.flutter.dev/flutter/widgets/State/deactivate.html) and [this is the dispose method](https://api.flutter.dev/flutter/widgets/State/dispose.html) – wafL Sep 11 '20 at 10:24
deactivate:
Called when object is removed from the tree. In some cases, the framework will reinsert the State object into another part of the tree (e.g., if the subtree containing this State object is grafted from one location in the tree to another). source
dispose:
Called when this object is removed from the tree permanently. source
By understanding both sentences, you'll see that deactivate will be called for widgets that are removed from the tree, temporarily or permanently, whereas dispose will only be called for widgets being removed permanently.
Thanks to Antonio Oliveira for the links, now I understand.

- 22,056
- 10
- 114
- 167
-
1In a nutshell, when `State` is removed from subtree A and reinserted to subtree B due to the use of a `GlobalKey`, only the `deactivate()` lifecycle method is invoked, `dispose()` is NOT called (hence, `State` is just deactivated but not disposed in this case). When a `State` is permanently removed from the tree, `deactivate()` is called first, and then `dispose()` is called later. – Son Nguyen Sep 21 '21 at 04:04
When a widget is removed from the tree, deactivate is called. However, the framework may decide to insert it again in another part of the widget tree. A good example would be when you reorder a list!
@override
void deactivate() {
super.deactivate();
}
Dispose is called when a widget is permanently removed from the tree. This has reached the end of its life cycle.
@override
void dispose() {
super.dispose();
}

- 5,491
- 3
- 31
- 44
"deactivate" refers to the process of removing a widget from the tree and calling its deactivate method. This happens when the widget's parent changes and the widget is removed from the tree.
"dispose" refers to the process of releasing resources used by a widget. This is usually done in the dispose method of the widget, which is called when the widget is removed from the tree and is no longer needed.
In summary, "deactivate" is a step in the process of removing a widget from the tree, while "dispose" is a method that is called when the widget is removed and is used to release resources.

- 506
- 4
- 8