WeakMap<K, V> class

A WeakMap lets you garbage-collect its keys. Please note: The key can be garbage-collected, not the value.

This means if you use some object as a key to a map-entry, this alone will not prevent Dart to garbage-collect this object. In other words, after all other references to that object have been destroyed, its entry (key and value) may be removed automatically from the map at any moment.

To create a map:

var map = WeakMap();

To add and retrieve a value:

map["John"] = 42;
var age = map["John"];

The following map methods work as expected:

map.remove("John")
map.clear()
map.contains("John"))

However, adding some null value to the map is the same as removing the key:

map["John"] = null; // Same as map.remove("John")

Notes:

  1. If you use null, a number, a boolean, a String, or a const type as the map key, it will act like a regular map, because these types are never garbage-collected. All other types of object may be garbage-collected.

  2. To retrieve a value added to the map, you can use the equivalent syntax var y = map[x] or var y = map.get(x).

Constructors

WeakMap()

Properties

hashCode int
The hash code for this object.
no setterinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

add({required K key, required V value}) → void
clear() → void
contains(K key) bool
get(K key) → V?
Returns the value associated with this key, or null if the key doesn't exist in the map. Note this can't differentiate between the key not existing and the value being null.
getOrThrow(K key) → V
Returns the value associated with this key. It will throw if the key doesn't exist in the map. Note this may only return null if V is nullable.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
remove(K key) → void
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited
operator [](K key) → V?
Returns the value associated with this key, or null if the key doesn't exist in the map. Note this can't differentiate between the key not existing and the value being null.
operator []=(K key, V value) → void