Dart – Whats equivalent of C# Stream/MemoryStream and stream.WriteByte(..) for Dart


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 to byte[] and also more efficient than List<int>. While I can add int8 in Uint8List but Uint8List can only be initialized with fixed-length. I need something dynamic where I can just say write or add without the need of any index to add. No idea how add() of Uint8List works. Couldn’t find much on the internet or in docs.


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 a Uint8List afterward.
  • Create your own class that wraps a Uint8List. When extra capacity is needed, you would need to allocate a new Uint8List that has, say, double the previous size, and to copy the old elements. (This is what most other growable list implementations (e.g. C++’s std::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 new Uint8List members as capacity is need and concatenating them into a single Uint8List when done. There is a third-party buffer package that can do this, but I have never personally used it and can’t vouch for it.

Answered By – jamesdlin

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *