readAsBytes function

Future<Uint8List> readAsBytes(
  1. Stream<List<int>> stream, {
  2. int? maxLength,
  3. bool copy = false,
})

Read stream into a typed byte buffer.

When maxLength is specified and reached, the returned future completes with an error.

copy controls whether the bytes the stream provides needs to be copied (e.g. because the underlying list may get modified).

Implementation

Future<Uint8List> readAsBytes(
  Stream<List<int>> stream, {
  int? maxLength,
  bool copy = false,
}) async {
  final bb = BytesBuffer();
  await for (List<int> next in stream) {
    bb.add(next);
    if (maxLength != null && maxLength < bb.length) {
      throw StateError('Max length reached: $maxLength bytes.');
    }
  }
  return bb.toBytes();
}