如何将 Stream<List<int>> 转换为 Flutter 中的 Stream<Uint8List>

huangapple go评论77阅读模式
英文:

How to transform Stream<List<int>> to Stream<Uint8List> in Flutter

问题

我有一个来自包的Flutter函数,返回一个Stream&lt;List&lt;int&gt;&gt;,我想将其转换为Stream&lt;Uint8List&gt;。我对Dart Streams不太熟悉,所以我会感激有关这个主题的任何帮助/建议。

我已经尝试过cast()as Stream&lt;Uint8List&gt;,但完全没有效果。

英文:

I have a Flutter function from a package that returns a Stream&lt;List&lt;int&gt;&gt; and I want to cast/transform to a Stream&lt;Uint8List&gt;. I'm not very familiar with dart Streams so I will appreciate any help/suggestion on this topic.

I have tried to cast(), as Stream&lt;Uint8List&gt;, but did not work at all.

答案1

得分: 3

以下是翻译好的部分:

"It's very likely that you have a Stream<List<int>> that already has Uint8List elements。如果是这样,您应该能够通过使用 Stream.cast 来将元素 (而不是 Stream 本身) 进行强制类型转换:

var uint8ListStream = originalStream.cast<Uint8List>();

如果这不起作用,那么您可以使用 Stream.map 从原始 Stream 中创建一个新的 Stream,将每个 List<int> 复制到新的 Uint8List 中:

var uint8ListStream = originalStream.map((list) => Uint8List.from(list));

您还可以使用上面链接的答案中的 asUint8List 来结合这些方法,只在必要时将其复制到新的 Uint8List 中:

var uint8ListStream = originalStream.map((list) => list.asUint8List());
英文:

It's very likely that you have a Stream&lt;List&lt;int&gt;&gt; that already has Uint8List elements. If so, you should be able to cast the elements (not the Stream itself) by using Stream.cast:

var uint8ListStream = originalStream.cast&lt;Uint8List&gt;();

If that doesn't work, then you can create a new Stream from the original with Stream.map, copying each List&lt;int&gt; into a new Uint8List:

var uint8ListStream = originalStream.map((list) =&gt; Uint8List.from(list));

You also could use asUint8List (from the answer I linked to above) to combine the approaches, copying into new Uint8Lists only if necessary:

var uint8ListStream = originalStream.map((list) =&gt; list.asUint8List());

huangapple
  • 本文由 发表于 2023年5月18日 01:58:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76274966.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定