Dart - Whats equivalent of C# Stream/MemoryStream and stream.WriteByte(..) for Dart
763
I don't believe that there is a standard equivalent. (There's a GitHub comment explaining why Uint8List
requires a fixed length.)
You instead could:
- Use
List<int>
and convert to aUint8List
afterward. - Create your own class that wraps a
Uint8List
. When extra capacity is needed, you would need to allocate a newUint8List
that has, say, double the previous size, and to copy the old elements. (This is what most other growable list implementations (e.g. C++'sstd::vector
) do.) Possibly there is some existing Dart package on pub.dev that already does this. - Make a class that wraps a
List<Uint8List>
, adding newUint8List
members as capacity is need and concatenating them into a singleUint8List
when done. There is a third-partybuffer
package that can do this, but I have never personally used it and can't vouch for it.
Author by
Rohit
Android Application Developer Hardcore PC Gamer Playing Android Games
Updated on December 09, 2022Comments
-
Rohit over 1 year
Need to achieve following in
dart
MemoryStream stream = new MemoryStream(288); stream.WriteByte((byte) 13); stream.WriteByte((byte) 12); stream.WriteByte((byte) 10); stream.WriteByte((byte) 8); stream.WriteByte((byte) 6); stream.WriteByte((byte) 9); var result = stream.ToArray();
I am coming from C#/java background and trying to use
Uint8List
which is equivalent tobyte[]
and also more efficient thanList<int>
. While I canadd
int8
inUint8List
butUint8List
can only be initialized with fixed-length. I need something dynamic where I can just saywrite
oradd
without the need of any index to add. No idea howadd()
ofUint8List
works. Couldn't find much on the internet or in docs. -
Rohit over 4 yearsIs there anything similar to Outputstream or stream to write data as we go?
-
jamesdlin over 4 years@Rohit I don't know what
Outputstream
is. If you're looking for something that can do efficient concatenation (like C++'sstd::stringstream
), I think the closest equivalent from the Dart SDK would beStringBuffer
. There is a third-partybuffer
package that does the same thing for byte data. -
Rohit over 4 years"Buffer package" looks promising, will give it a try. May be the thing I am looking for! Thanks
-
jamesdlin over 4 yearsI forgot to note that I've never used and can't vouch for the
buffer
package; it was just the first result when I searched for "buffer" on pub.dev. -
Rohit over 4 yearsNever popped that result for me, may be I was searching different terms like "streams".
-
Rohit over 4 yearsCan you edit your answer with buffer package as a solution.
buffer
package hasByteDataWriter
which does exactly what I mentioned in the code example in the question. @jamesdlin -
jamesdlin over 4 years@Rohit Okay, done. (The other approaches I mentioned could do exactly what you mentioned in your code example too. ;) )