readLineSync 方法

String? readLineSync(
  1. {Encoding encoding = systemEncoding,
  2. bool retainNewlines = false}
)

从标准输入(stdin)读取一行。

会阻塞,直到可用完整行。

行可能由 <CR><LF><LF> 结束。在 Windows 上,如果 stdin 的 stdioTypeStdioType.terminal,终止符也可能是一个单独的 <CR>

使用 encoding 将输入字节转换为字符串。如果省略了 encoding,则默认为 systemEncoding

如果 retainNewlinesfalse,则返回的字符串不会包含最后的行终止符。如果为 true,则返回的字符串将包含行终止符。默认为 false

如果在从 stdin 读取任何字节后到达文件末尾,则返回该数据,无行终止符。如果没有字节在输入末尾之前,则返回 null

实现

String? readLineSync(
    {Encoding encoding = systemEncoding, bool retainNewlines = false}) {
  const CR = 13;
  const LF = 10;
  final List<int> line = <int>[];
  // On Windows, if lineMode is disabled, only CR is received.
  bool crIsNewline = Platform.isWindows &&
      (stdioType(stdin) == StdioType.terminal) &&
      !lineMode;
  if (retainNewlines) {
    int byte;
    do {
      byte = readByteSync();
      if (byte < 0) {
        break;
      }
      line.add(byte);
    } while (byte != LF && !(byte == CR && crIsNewline));
    if (line.isEmpty) {
      return null;
    }
  } else if (crIsNewline) {
    // CR and LF are both line terminators, neither is retained.
    while (true) {
      int byte = readByteSync();
      if (byte < 0) {
        if (line.isEmpty) return null;
        break;
      }
      if (byte == LF || byte == CR) break;
      line.add(byte);
    }
  } else {
    // Case having to handle CR LF as a single unretained line terminator.
    outer:
    while (true) {
      int byte = readByteSync();
      if (byte == LF) break;
      if (byte == CR) {
        do {
          byte = readByteSync();
          if (byte == LF) break outer;

          line.add(CR);
        } while (byte == CR);
        // Fall through and handle non-CR character.
      }
      if (byte < 0) {
        if (line.isEmpty) return null;
        break;
      }
      line.add(byte);
    }
  }
  return encoding.decode(line);
}