AutoCloseable class abstract

An object that may hold resources (such as file or socket handles) until it is closed.

The close method of an AutoCloseable object is called automatically when exiting a try-finally block or using Dart's resource management patterns. This construction ensures prompt release, avoiding resource exhaustion exceptions and errors that may otherwise occur.

API Note

It is possible, and in fact common, for a base class to implement AutoCloseable even though not all of its subclasses or instances will hold releasable resources. For code that must operate in complete generality, or when it is known that the AutoCloseable instance requires resource release, it is recommended to use try-finally constructions or Dart's resource management patterns.

Example Usage

class FileResource implements AutoCloseable {
  final File _file;
  bool _closed = false;
  
  FileResource(String path) : _file = File(path);
  
  String readContent() {
    if (_closed) throw NoGuaranteeException('Resource is closed');
    return _file.readAsStringSync();
  }
  
  @override
  void close() {
    if (!_closed) {
      _closed = true;
      // Cleanup resources here
      print('File resource closed');
    }
  }
}

// Usage with try-finally
void useResource() {
  final resource = FileResource('example.txt');
  try {
    final content = resource.readContent();
    print(content);
  } finally {
    resource.close();
  }
}

// Usage with helper function
T useResourceSafely<T>(AutoCloseable resource, T Function() action) {
  try {
    return action();
  } finally {
    resource.close();
  }
}
Implementers

Constructors

AutoCloseable()
An object that may hold resources (such as file or socket handles) until it is closed.

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

close() FutureOr<void>
Closes this resource, relinquishing any underlying resources.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited