如何创建流并将其与 StreamBuilder() 一起使用。 我需要像 Firebase Cloud Firestore 一样实时传输外部存储目录,并获取信息(如果存储具有我搜索的当前文件)。例如,我有从应用程序下载的视频或图像,并且想要监听外部存储目录以实时显示文件。当我删除任何文件时,它会从屏幕上删除。
最佳答案
StreamBuilder
widget 对于这种情况确实很有用,你可以查看文档 here .
首先,什么是流?将其想象为一根 pipe ,事物在 pipe 的一侧异步传递(意味着并非所有项目同时传递);并且,在未来的某个时刻,这些元素会再次异步到达管道的另一端。
现在,知道什么是 Stream
是,我们必须意识到,我们不知道我们的请求何时结束,它可能永远不会结束!因此,Flutter 为我们提供了StreamBuilder
小部件。假设您的 Firebase 实例返回 Stream<List<Item>>
命名getListOfItems
。使用StreamBuilder
,你可以这样做:
//... 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();
}
}
)
这对于 StreamBuilder
的任何基本实现都应该如此。 。从这里您可以构建动态列表、分页等等!
关于Flutter Streams 的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68619277/