Flutter 流的使用

Flutter Streams usage

如何创建流并将其与 StreamBuilder() 一起使用。 我需要像 Firebase Cloud Firestore 一样实时流式传输外部存储目录,并在存储有我搜索的当前文件时获取信息。例如,我有从我的应用程序下载的视频或图像,并且想收听外部存储目录以实时显示文件。当我删除任何文件时,它会从屏幕上删除。

StreamBuilder widget 对这种情况真的很有用,你可以查看文档 here.

首先,什么是流?把它想象成一个管子,东西在管子的一侧异步传递(意味着不是所有的东西都同时传递);并且,在未来的某个时刻,这些物品再次异步到达管道的另一端。

现在,知道什么是Stream,我们必须意识到我们不知道我们的请求何时结束,它可能永远不会结束!因此,Flutter 为我们提供了 StreamBuilder widget。假设您的 Firebase 实例 returns 是一个名为 getListOfItemsStream<List<Item>>。使用 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 的任何基本实现都应该如此。从这里您可以构建动态列表、分页等等!