readLine method
Reads a line of text.
A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
Returns
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached.
Example
final reader = FileReader('lines.txt');
try {
String? line;
int lineNumber = 1;
while ((line = await reader.readLine()) != null) {
print('Line $lineNumber: $line');
lineNumber++;
}
} finally {
await reader.close();
}
Throws IOException if an I/O error occurs. Throws StreamClosedException if the reader has been closed.
Implementation
Future<String?> readLine() async {
checkClosed();
final buffer = StringBuffer();
int char;
while ((char = await readChar()) != -1) {
if (char == 10) { // '\n'
break;
} else if (char == 13) { // '\r'
// Check for '\r\n'
final nextChar = await readChar();
if (nextChar != -1 && nextChar != 10) {
// Put back the character if it's not '\n'
// This is a simplified implementation - real implementation would use mark/reset
}
break;
} else {
buffer.writeCharCode(char);
}
}
if (buffer.isEmpty && char == -1) {
return null; // End of stream
}
return buffer.toString();
}