英文:
How to transform Stream<List<int>> to Stream<Uint8List> in Flutter
问题
我有一个来自包的Flutter函数,返回一个Stream<List<int>>
,我想将其转换为Stream<Uint8List>
。我对Dart Streams不太熟悉,所以我会感激有关这个主题的任何帮助/建议。
我已经尝试过cast()
、as Stream<Uint8List>
,但完全没有效果。
英文:
I have a Flutter function from a package that returns a Stream<List<int>>
and I want to cast/transform to a Stream<Uint8List>
. 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<Uint8List>
, 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<List<int>>
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<Uint8List>();
If that doesn't work, then you can create a new Stream
from the original with Stream.map
, copying each List<int>
into a new Uint8List
:
var uint8ListStream = originalStream.map((list) => Uint8List.from(list));
You also could use asUint8List
(from the answer I linked to above) to combine the approaches, copying into new Uint8List
s only if necessary:
var uint8ListStream = originalStream.map((list) => list.asUint8List());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论