【问题标题】:Restart StreamBuilder with multiple streams after ConnectionState.done在 ConnectionState.done 之后使用多个流重新启动 StreamBuilder
【发布时间】:2020-09-02 11:42:14
【问题描述】:

当您想在 StreamBuilder 中使用多个流时,有什么好方法可以重新启动 StreamBuilder 以使用下一个流?

现在,我正在通过在标志 (_streamCompleted) 上使用 setState 来检查流是否已完成。

但我想知道在 ConnectionState.done 被触发后是否可以重用 StreamBuilder。

 Stream donwloadStream = response.stream.map(processDownload);

...

StreamBuilder(
    stream: _streamIndex == null ? null : streams[_streamIndex].stream,
    builder: (context, snapshot) {

      if (ConnectionState.done) {
        // How do I switch to the next stream here ???
      }

这是我检查是否完成的方式:

double processDownload(List<int> chunk) {
    bytes.addAll(chunk);
    cnt = bytes.length;
    double progress = cnt / streams[_streamIndex].contentLength;

    if (cnt / streams[_streamIndex].contentLength == 1) {
      setState(() {           
          _streamCompleted = true;
          _streamIndex++;
      });
    }
     return progress;
 }

我也尝试过使用 CombineLatestStream,但无法让流开始触发,ConnectionState 为无。

StreamBuilder(
            stream: _combinedStreams == null ? null : _combinedStreams,

    setState(() {
      _combinedStreams =
          CombineLatestStream.list([streams[0].stream, streams[1].stream, streams[2].stream])
              .asBroadcastStream();
    });

  _combinedStreams.listen((event) {});

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    只需使用两个流生成器。

    StreamBuilder(
        stream: _streamIndex == null ? null : streams[_streamIndex].stream,
        builder: (context, snapshot) {
          if (ConnectionState.done) {
            StreamBuilder(
                stream: _stream2 == null ? null : streams2.stream,
                builder: (context, snapshot2) {...
    

    【讨论】:

    • 谢谢,我知道嵌套构建器可以工作,但问题是我有未知数量的流,所以宁愿不使用这个解决方案。
    猜你喜欢
    • 2021-10-27
    • 2021-02-21
    • 1970-01-01
    • 2021-02-20
    • 2019-11-03
    • 2021-01-09
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    相关资源
    最近更新 更多