5

飞镖程序员。

我正在使用 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;
    });

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

4

2 回答 2

6

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

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
于 2014-10-02T05:12:54.113 回答
3

虽然@Günter Zöchbauer 的答案有效,但last流的属性完全符合您的要求(我猜飞镖团队在过去 5 年中添加了此功能)。

Stream<List<int>> stream = new File('main.dart').openRead();
List<int> last = await stream.last;

但请注意:无法收听流并使用await stream.last.

这将导致错误:

StateError(错误状态:Stream 已被监听。)

于 2020-03-08T14:14:52.467 回答