如何在 Dart 中检查 Stream 的结束?

seo*_*joo 5 dart dart-async

各位 Dart 程序员。

我正在使用 Stream 读取文件,如下所示。

Stream<List<int>> stream = new File(filepath).openRead();
stream
    .transform(UTF8.decoder)
    .transform(const LineSpilitter())
    .listen((line){
        // TODO: check if this is the last line of the file
        var isLastLine;
    });
Run Code Online (Sandbox Code Playgroud)

我想检查listen()中的行是否是文件的最后一行。

Gün*_*uer 5

我认为您无法检查当前数据块是否是最后一个。
您只能传递关闭流时调用的回调。

Stream<List<int>> stream = new File('main.dart').openRead();
  stream.
  .transform(UTF8.decoder)
  .transform(const LineSpilitter())
  .listen((line) {
// TODO: check if this is the last line of the file
    var isLastLine;
  }
  ,onDone: (x) => print('done')); // <= add a second callback
Run Code Online (Sandbox Code Playgroud)

  • 我明白。您可以做的是缓冲最后一行,并在收到下一行后才处理它。`onDone` 你处理最后一个缓冲的行。 (2认同)