close method

  1. @override
Future<void> close()
override

Closes the stream, flushing it first.

Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect.

Example

final writer = FileWriter('output.txt');
try {
  await writer.write('Hello, World!');
  // flush() is called automatically by close()
} finally {
  await writer.close(); // Always close in finally block
}

Throws IOException if an I/O error occurs.

Implementation

@override
Future<void> close() async {
  if (!isClosed) {
    try {
      await flush();
      await _randomAccessFile?.close();
    } catch (e) {
      throw IOException('Error closing file: ${_file.path}', cause: e);
    } finally {
      _randomAccessFile = null;
      _buffer.clear();
      await super.close();
    }
  }
}