readByteStream function
Read all bytes from input
and return a Uint8List consisting of all bytes
from input
.
If the maximum number of bytes exceeded maxSize
this will stop reading and
throw MaximumSizeExceeded.
Example
import 'dart:io';
Uint8List readFile(String filePath) async {
Stream<List<int>> fileStream = File(filePath).openRead();
Uint8List contents = await readByteStream(fileStream);
return contents;
}
This method does the same as readChunkedStream, except it returns a Uint8List which can be faster when working with bytes.
Remark The returned Uint8List might be a view on a larger ByteBuffer. Do not use Uint8List.buffer without taking into account Uint8List.lengthInBytes and Uint8List.offsetInBytes. Doing so is never correct, but in many common cases an instance of Uint8List will not be a view on a larger buffer, so such mistakes can go undetected. Consider using Uint8List.sublistView, to create subviews if necessary.
Implementation
Future<Uint8List> readByteStream(
Stream<List<int>> input, {
int? maxSize,
}) async {
if (maxSize != null && maxSize < 0) {
throw ArgumentError.value(maxSize, 'maxSize must be positive, if given');
}
final result = BytesBuilder();
await for (final chunk in input) {
result.add(chunk);
if (maxSize != null && result.length > maxSize) {
throw MaximumSizeExceeded(maxSize);
}
}
return result.takeBytes();
}