fellow dart programmers.
I am reading in a file using Stream as below.
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;
});
I want to check whether the line in listen() is the last line of the file.
Cancel a stream In flutter, streams are usually used with the StreamBuilder which manages and unsubscribes from a stream for you internally once the widget is destroyed. A good rule to follow is when you subscribe to a stream, keep the Subscription and write the code in the dispose method to call cancel.
To create a new Stream type, you can just extend the Stream class and implement the listen() method—all other methods on Stream call listen() in order to work. The listen() method allows you to start listening on a stream. Until you do so, the stream is an inert object describing what events you want to see.
A subscription on events from a Stream. When you listen on a Stream using Stream. listen, a StreamSubscription object is returned. The subscription provides events to the listener, and holds the callbacks used to handle the events.
I don't think you can check if the current chunk of data is the last one.
You can only pass a callback that is called when the stream is closed.
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
While the answer from @Günter Zöchbauer works, the last
property of streams accomplishes exactly what you are asking for (I guess the dart team added this functionality in the last 5 years).
Stream<List<int>> stream = new File('main.dart').openRead();
List<int> last = await stream.last;
But note: It is not possible to listen to the stream and use await stream.last
.
This will cause an error:
StateError (Bad state: Stream has already been listened to.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With