19

I want to basically delete an object I created. How do we delete an object?

I checked Object definition here, but couldn't figure out way to do it. Also I am curious whether we can define destructors or not.

UPDATE The question is getting good answers. But I want to draw your attention to a case in which I want to delete my objects or call destructor. Let's say we want to create a pace using that you can connect rectangles via the ports placed on it. So the idea is to have an object that has a reference to the body of the rectangle and the ports placed at two ends. In fact, that object might need some other properties like [bool] selected or [bool] dragging or [List<RectElement>] connectedSquares. For example, when user selects the rectangle and hits backspace, I want to make sure the rectangles are gone and my object is properly deleted. So this use case may give some more insight into the question.

mert
  • 1,942
  • 2
  • 23
  • 43
  • 2
    Far as i can see in the docs, you don't. Garbage collection takes care of unreachable objects, so you don't have to do anything about them. (Main side effect being, you really *can't* do anything about them, other than triggering a GC cycle if the runtime provides some way to do that.) – cHao Dec 09 '13 at 23:04

5 Answers5

30

You don't need to actively delete objects in Dart.

Dart is a garbage-collected language, so any object that you don't hold any references to will eventually be garbage collected and freed by the runtime system.

So all you have to do is to clear any variables you have that reference the object.

Garbage collection is really implicit in the language specification. The specification doesn't say so that garbage collection exists (it doesn't even mention the concept), but the language and libraries are designed in such a way that garbage collection is possible: Objects that the program cannot find a reference to anywhere also can't affect the program's behavior any more, so it is undetectable that they are being collected and deleted by the garbage collector.

lrn
  • 64,680
  • 7
  • 105
  • 121
14

Make sure that you don't hold a reference to the object so it can be GCed.

x = null;
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
3

For the time being, Dart programs are deployed as JavaScripts, and are therefore limited to the JavaScript runtime model. Look for example at this question that clarifies that the only way to delete objects in JavaScript is by means of the garbage collector. If you call remove, or removeAt, etc. on your connectedSquares and don't hold any other references, this accomplishes what you are looking for.

As for destructors, the same limitations apply. If the object that holds references to "the body of the rectangle and the ports placed at two ends" becomes unreachable, everything it references becomes eligible for garbage collection as well - again, provided there are no other references.

In general, if you want a full understanding of the runtime semantics of Dart, it is (for now) necessary to understand JavaScript as well, look at compiled code, and learn by analogy.

Community
  • 1
  • 1
Tilo
  • 3,255
  • 26
  • 31
  • There are many garbage collected languages (including Java and C#), so Dart would probably have been garbage collected even if JavaScript wasn't (well, at least if it could still be compiled to efficient JavaScript anyway). Being garbage collected isn't something Dart is sorry about, and not something that's going to change (it's not just "for the time being"). – lrn Dec 11 '13 at 15:32
  • I believe you might have taken my comment the wrong way: I wasn't arguing against garbage collected languages (nor in their favor for that matter). My point was that while Dart is being deployed as compiled JS it doesn't have a choice. When native Dart runtime environments are in general use, Google will be pretty much free to evolve the language in whatever direction they see fit - including changes to the memory management model. – Tilo Dec 13 '13 at 01:13
3

Some additional note on deleting.

Limitations of JavaScript is affecting dart.

  • No reference count available
    This is javascript feature and partly because of the way garbage collection works in browser: What is JavaScript garbage collection?
  • No weak reference available(For the time being)
    Another Java-script limitation and because of the lack of access to reference count, self deleting is not an option either.
    Note:There is Expando and while it is useful, it's not a weak reference equivalent. Weak reference allows you to create ghost references that don't keep the object alive: https://en.wikipedia.org/wiki/Weak_reference.
  • No destructor available
    javascript does not have it, thus neither does dart.

As the others pointed, the limitations above are usually nothing.
Since the main eventloop can keep objects alive, careless coding could spawn an zombie object though; without destructor or weakref, some references could escape your murderous hands by accident and keep the object alive.

import 'dart:html';
import 'dart:async';
import 'dart:developer';

void main() {
  var e = new XXX();
  var ce = new CustomEvent('custom-event');
  var s = new Stream.periodic(new Duration(microseconds: 10000),(count) {
    print(count);
    window.dispatchEvent(ce);
    return count;
  });
  StreamSubscription ss = s.listen((count){print('stream runnig; ${count}_th run');});
//  e.destroy();
//  ss.cancel();
  e = null;
  s = null;
}
class XXX{
  StreamSubscription subscription;
  XXX(){
    subscription = window.on['custom-event'].listen(event_handler);
  }
  void say_hi(){
    print('hi');
    print(this);
  }
  void event_handler(_){this.say_hi();}
  destroy(){
    subscription.cancel();
  }
}

The above code prints the below in forever loop(unless you uncomment the two lines):

 ....
hi
VM33:1 Instance of 'XXX'
VM34:1 stream runnig; 751_th run
VM34:1 752
VM33:1 hi
VM33:1 Instance of 'XXX'
VM34:1 stream runnig; 752_th run
......

I don't know if the object e would persist without print(this), maybe only related objects are kept from garbage collection.

In any case, with more complicated code, manual clean up is necessary and I wish one of the three missing features is there but there is not.

Deleting indeed can be hard.

Community
  • 1
  • 1
TastyCatFood
  • 1,632
  • 1
  • 15
  • 27
  • See also https://github.com/dart-lang/sdk/issues/5144 and https://github.com/dart-lang/sdk/commit/75d1366dbd76566b562248a9d1ba3fbf5f339b41 for ongoing work on weak references. I don't really understand what problem you want to point out. What behavior do you expect? As long as an object is referenced from "active" objects (transitively referenced from main or the event loop), it doesn't get garbage collected. – Günter Zöchbauer Feb 06 '16 at 15:45
  • @Günter Zöchbauer Thanks, I see I was wrong about weak reference. I will fix the post. As to what's unexpected for me, I first leaned C++ and then python and there events don't always keep objects alive:http://stackoverflow.com/questions/17211797/does-pyqt4-signal-connect-keep-objects-live. I see the advantage of javascript way and in retrospect yes, it's obvious but I did fall. – TastyCatFood Feb 07 '16 at 06:00
  • I don't have deep insight in this topic myself. @lrn could explain it better what's exactly going on. – Günter Zöchbauer Feb 07 '16 at 06:04
-1

To delete an object in Flutter, you don't explicitly call a destructor or delete the object like in some other programming languages. Dart, the language used in Flutter, has a garbage collector that automatically cleans up memory when objects are no longer reachable. When there are no more references to an object, it becomes eligible for garbage collection.

In your specific use case of deleting rectangles and ensuring that associated objects are properly deleted, you can follow these steps:

  1. Create a class to represent the rectangle object, along with any additional properties and references you need. For example:
class Rectangle {
  // Properties and references of the rectangle object
}
  1. Create an object that holds references to the rectangles and manages their deletion. You can use a list or another data structure to store the rectangles. For example:
class RectangleManager {
  List<Rectangle> rectangles = [];

  // Other methods and logic for managing the rectangles
}
  1. When a rectangle is selected for deletion, remove it from the list or data structure:
// invoke this function when the user press back (like using GestureDetector)
void deleteRectangle(Rectangle rectangle) {
  rectangleManager.rectangles.remove(rectangle);
  // Perform any additional cleanup or actions associated with the deletion
}
  1. Ensure that all references to the deleted rectangle are removed. This includes any other objects that hold references to the rectangle or its associated properties.

By removing the references to the rectangle object, you allow the Dart garbage collector to automatically clean up the memory associated with the deleted object when it determines that the object is no longer reachable.

Dart does not have explicit destructors like some other languages. The garbage collector handles the memory management, and you can rely on it to clean up objects that are no longer in use.

References: