Appearance
NativeFinalizer abstract final
abstract final class NativeFinalizerAnnotations: @Since.new('2.17')
A native finalizer which can be attached to Dart objects.
When attached to a Dart object, this finalizer's native callback is called after the Dart object is garbage collected or becomes inaccessible for other reasons.
Callbacks will happen as early as possible, when the object becomes inaccessible to the program, and may happen at any moment during execution of the program. At the latest, when an isolate group shuts down, this callback is guaranteed to be called for each object in that isolate group that the finalizer is still attached to.
Compared to the Finalizer from dart:core, which makes no promises to ever call an attached callback, this native finalizer promises that all attached finalizers are definitely called at least once before the isolate group shuts down, and the callbacks are called as soon as possible after an object is recognized as inaccessible.
Note that an isolate group is not necessarily guaranteed to shutdown normally as the whole process might crash or be abruptly terminated by a function like exit. This means NativeFinalizer can not be relied upon for running actions on the programs exit.
When the callback is a Dart function rather than a native function, use Finalizer instead.
A native finalizer can be used to close native resources. See the following example.
dart
/// [Database] enables interacting with the native database.
///
/// After [close] is called, cannot be used to [query].
///
/// If a [Database] is garbage collected, it is automatically closed by
/// means of a native finalizer. Prefer closing manually for timely
/// release of native resources.
///
/// Note this class is incomplete and for illustration purposes only.
class Database implements Finalizable {
/// The native finalizer runs [_closeDatabasePointer] on [_nativeDatabase]
/// if the object is garbage collected.
///
/// Keeps the finalizer itself reachable, otherwise it might be disposed
/// before the finalizer callback gets a chance to run.
static final _finalizer =
NativeFinalizer(_nativeDatabaseBindings.closeDatabaseAddress.cast());
/// The native resource.
///
/// Should be closed exactly once with [_closeDatabase] or
/// [_closeDatabasePointer].
Pointer<_NativeDatabase> _nativeDatabase;
/// Used to prevent double close and usage after close.
bool _closed = false;
Database._(this._nativeDatabase);
/// Open a database.
factory Database.open() {
final nativeDatabase = _nativeDatabaseBindings.openDatabase();
final database = Database._(nativeDatabase);
_finalizer.attach(database, nativeDatabase.cast(), detach: database);
return database;
}
/// Closes this database.
///
/// This database cannot be used anymore after it is closed.
void close() {
if (_closed) {
return;
}
_closed = true;
_finalizer.detach(this);
_nativeDatabaseBindings.closeDatabase(_nativeDatabase);
}
/// Query the database.
///
/// The database should not have been closed.
void query() {
if (_closed) {
throw StateError('The database has been closed.');
}
// Query the database.
}
}
final _nativeDatabaseBindings = _NativeDatabaseLib(DynamicLibrary.process());
// The following classes are typically generated with `package:ffigen`.
// Use `symbol-address` to expose the address of the close function.
class _NativeDatabaseLib {
final DynamicLibrary _library;
_NativeDatabaseLib(this._library);
late final openDatabase = _library.lookupFunction<
Pointer<_NativeDatabase> Function(),
Pointer<_NativeDatabase> Function()>('OpenDatabase');
late final closeDatabaseAddress =
_library.lookup<NativeFunction<Void Function(Pointer<_NativeDatabase>)>>(
'CloseDatabase');
late final closeDatabase = closeDatabaseAddress
.asFunction<void Function(Pointer<_NativeDatabase>)>();
}
final class _NativeDatabase extends Opaque {}Constructors
NativeFinalizer() factory
factory NativeFinalizer(
Pointer<NativeFinalizerFunction<Void Function(Pointer<Void> token)>> callback,
)Creates a finalizer with the given finalization callback.
The callback must be a native function which can be executed outside of a Dart isolate. This also means that passing an FFI trampoline (a function a function pointer obtained via Pointer.fromFunction) is not supported.
The callback is not allowed to re-enter the Dart VM via Dart C APIs, with two exceptions: it is allowed to call Dart_DeletePersistentHandle and Dart_DeleteWeakPersistentHandle. Calling any other Dart C API function results in undefined behavior, which means it can cause anything from crashes and deadlocks to silent memory corruptions.
The callback might be invoked on an arbitrary thread. It will have a current isolate group but will not have a current isolate.
Implementation
dart
external factory NativeFinalizer(Pointer<NativeFinalizerFunction> callback);Properties
hashCode no setter inherited
int get hashCodeThe hash code for this object.
A hash code is a single integer which represents the state of the object that affects operator == comparisons.
All objects have hash codes. The default hash code implemented by Object represents only the identity of the object, the same way as the default operator == implementation only considers objects equal if they are identical (see identityHashCode).
If operator == is overridden to use the object state instead, the hash code must also be changed to represent that state, otherwise the object cannot be used in hash based data structures like the default Set and Map implementations.
Hash codes must be the same for objects that are equal to each other according to operator ==. The hash code of an object should only change if the object changes in a way that affects equality. There are no further requirements for the hash codes. They need not be consistent between executions of the same program and there are no distribution guarantees.
Objects that are not equal are allowed to have the same hash code. It is even technically allowed that all instances have the same hash code, but if clashes happen too often, it may reduce the efficiency of hash-based data structures like HashSet or HashMap.
If a subclass overrides hashCode, it should override the operator == operator as well to maintain consistency.
Inherited from Object.
Implementation
dart
external int get hashCode;runtimeType no setter inherited
Type get runtimeTypeA representation of the runtime type of the object.
Inherited from Object.
Implementation
dart
external Type get runtimeType;Methods
attach()
void attach(
Finalizable value,
Pointer<Void> token, {
Object? detach,
int? externalSize,
})Attaches this finalizer to value.
When value is no longer accessible to the program, the finalizer will call its callback function with token as argument.
If a non-null detach value is provided, that object can be passed to Finalizer.detach to remove the attachment again.
The value and detach arguments do not count towards those objects being accessible to the program. Both must be objects supported as an Expando key. They may be the same object.
Multiple objects may be using the same finalization token, and the finalizer can be attached multiple times to the same object with different, or the same, finalization token.
The callback will be called exactly once per attachment, except for registrations which have been detached since they were attached.
The externalSize should represent the amount of native (non-Dart) memory owned by the given value. This information is used for garbage collection scheduling heuristics.
Implementation
dart
void attach(
Finalizable value,
Pointer<Void> token, {
Object? detach,
int? externalSize,
});detach()
void detach(Object detach)Detaches this finalizer from values attached with detach.
If this finalizer was attached multiple times to the same object with different detachment keys, only those attachments which used detach are removed.
After detaching, an attachment won't cause any callbacks to happen if the object become inaccessible.
Implementation
dart
void detach(Object detach);noSuchMethod() inherited
dynamic noSuchMethod(Invocation invocation)Invoked when a nonexistent method or property is accessed.
A dynamic member invocation can attempt to call a member which doesn't exist on the receiving object. Example:
dart
dynamic object = 1;
object.add(42); // Statically allowed, run-time errorThis invalid code will invoke the noSuchMethod method of the integer 1 with an Invocation representing the .add(42) call and arguments (which then throws).
Classes can override noSuchMethod to provide custom behavior for such invalid dynamic invocations.
A class with a non-default noSuchMethod invocation can also omit implementations for members of its interface. Example:
dart
class MockList<T> implements List<T> {
noSuchMethod(Invocation invocation) {
log(invocation);
super.noSuchMethod(invocation); // Will throw.
}
}
void main() {
MockList().add(42);
}This code has no compile-time warnings or errors even though the MockList class has no concrete implementation of any of the List interface methods. Calls to List methods are forwarded to noSuchMethod, so this code will log an invocation similar to Invocation.method(#add, [42]) and then throw.
If a value is returned from noSuchMethod, it becomes the result of the original invocation. If the value is not of a type that can be returned by the original invocation, a type error occurs at the invocation.
The default behavior is to throw a NoSuchMethodError.
Inherited from Object.
Implementation
dart
@pragma("vm:entry-point")
@pragma("wasm:entry-point")
external dynamic noSuchMethod(Invocation invocation);toString() inherited
String toString()A string representation of this object.
Some classes have a default textual representation, often paired with a static parse function (like int.parse). These classes will provide the textual representation as their string representation.
Other classes have no meaningful textual representation that a program will care about. Such classes will typically override toString to provide useful information when inspecting the object, mainly for debugging or logging.
Inherited from Object.
Implementation
dart
external String toString();Operators
operator ==() inherited
The equality operator.
The default behavior for all Objects is to return true if and only if this object and other are the same object.
Override this method to specify a different equality relation on a class. The overriding method must still be an equivalence relation. That is, it must be:
Total: It must return a boolean for all arguments. It should never throw.
Reflexive: For all objects
o,o == omust be true.Symmetric: For all objects
o1ando2,o1 == o2ando2 == o1must either both be true, or both be false.Transitive: For all objects
o1,o2, ando3, ifo1 == o2ando2 == o3are true, theno1 == o3must be true.
The method should also be consistent over time, so whether two objects are equal should only change if at least one of the objects was modified.
If a subclass overrides the equality operator, it should override the hashCode method as well to maintain consistency.
Inherited from Object.
Implementation
dart
external bool operator ==(Object other);