Answer
Overview
Dart does not have a traditional "destructor" like C++ (
text
~ClassName()text
dispose()Dart Memory Management
Dart uses an automatic garbage collector — memory is freed when objects are no longer referenced. You don't manually destroy objects.
dartvoid main() { var obj = HeavyObject(); // Created in heap obj.doSomething(); // When obj goes out of scope or is reassigned, // GC eventually frees the memory — no destructor needed obj = null; // ← hints it can be collected (if nullable) }
The Finalizer Class (Dart 2.17+)
Dart 2.17 introduced
text
Finalizerdartfinal finalizer = Finalizer<String>((message) { print('Object collected: $message'); }); class Resource { Resource() { finalizer.attach(this, 'Resource cleanup', detach: this); } void close() { finalizer.detach(this); // Manual cleanup } }
⚠️
is not deterministic — you don't know exactly when it runs. Prefer explicittextFinalizer.textdispose()
dispose() — Flutter's Lifecycle Teardown
In Flutter, the closest equivalent to a destructor is
text
dispose()text
Statedartclass MyScreen extends StatefulWidget { _MyScreenState createState() => _MyScreenState(); } class _MyScreenState extends State<MyScreen> with SingleTickerProviderStateMixin { late AnimationController _controller; late StreamSubscription _subscription; late TextEditingController _textController; void initState() { super.initState(); _controller = AnimationController(vsync: this, duration: Duration(seconds: 1)); _subscription = dataStream.listen((data) => setState(() {})); _textController = TextEditingController(); } void dispose() { // 'Destructor' — called when widget is removed from tree _controller.dispose(); _subscription.cancel(); _textController.dispose(); super.dispose(); } Widget build(BuildContext context) => Container(); }
Other Dispose Patterns
dart// ChangeNotifier class MyNotifier extends ChangeNotifier { Timer? _timer; void startTimer() { _timer = Timer.periodic(Duration(seconds: 1), (_) {}); } void dispose() { _timer?.cancel(); // Clean up timer super.dispose(); } } // GetX Controller class MyController extends GetxController { void onClose() { // Destructor equivalent in GetX super.onClose(); } }
Summary
| Language | Destructor |
|---|---|
| C++ | text |
| Dart | No destructor — GC handles memory |
| Flutter Widget | text |
| GetX Controller | text |
| Dart (advanced) | text |
Best Practice: Always override
intextdispose()State classes to clean uptextStatefulWidget,textAnimationController,textTextEditingController,textStreamSubscription, andtextTimerobjects to prevent memory leaks.textFocusNode