How to create stream and use it with StreamBuilder(). I need to stream External Storage Directory in real time like as Firebase Cloud Firestore and get info if storage have current file which I search. For example, I have videos or images which I downloaded from my application, and want to listen external storage directory to show files in real time. And when I delete any file it removes from screen.
StreamBuilder
widget is really useful for such cases, you can check the documentation here.
First of all, what is a stream? Imagine it like a tube, where things are passed in one side of the tube, asynchronously (meaning not all items are passed at the same time); and, at some point of the future, those items arrive at the other end of the tube, again, asynchronously.
Now, knowing what a Stream
is, we have to realise that we do not know when our request will end, it may never end! Therefore, Flutter provides us with the StreamBuilder
widget. Let's say that your Firebase instance returns a Stream<List<Item>>
named getListOfItems
. Using the StreamBuilder
, you could do:
//... As a child of any of your widgets
StreamBuilder(
stream: instance.getListOfItems(), // <-- We simply pass the function that returns the stream, Flutter will manage the rest!
builder: (ctx, snapshot) {
// The snapshot contains the data that is being recieved if any
// you can check the docs:
// https://api.flutter.dev/flutter/widgets/AsyncSnapshot-class.html
// And for the ConnectionState enum
// https://api.flutter.dev/flutter/widgets/ConnectionState-class.html
if (snapshot.connectionState == ConnectionState.waiting) {
// What should be rendered when loading or waiting for a response?
return Loading();
}
if (snapshot.hasData) {
// What should be rendered when there's data?
// Remember, data may keep arriving
return MyList(snapshot.data);
}
if (snapshot.hasError) {
// Wow, the stream failed, what should be rendered when there's an error?
return Error();
}
}
)
That should do for any basic implementation of the StreamBuilder
. From here you can build dynamic lists, pagination and more!