Dart fill ByteData with List<int>

Viewed 426
List<int> l = [ 1, 2, 3, 4 ];
var b = ByteData(10);

May I know what is the easiest way to fill b (position 4 ~ 7) with data from l.

I can certainly iterate through l and then fill b one by one. But this is just part of a larger solution. So I hope there is a simpler way (for easy maintenance in future).

1 Answers

ByteData represent an area of memory counted in bytes but does not tell us anything how we want to represent the data inside this block of memory.

Normally, we would use one of the specific data types from dart:typed_data like e.g. Uint8List, Int8List, Uint16List and so on which have a lot more functionality.

But you can easily get the same by making a view over your ByteData. In this example I guess you want to insert your numbers as Uint8:

import 'dart:typed_data';

void main() {
  List<int> l = [ 1, 2, 3, 4 ];
  var b = ByteData(10);
  var uInt8ListViewOverB = b.buffer.asUint8List();
  uInt8ListViewOverB.setAll(4, l);
  print(uInt8ListViewOverB); // [0, 0, 0, 0, 1, 2, 3, 4, 0, 0]
}

I recommend reading the documentation for the different methods on ByteBuffer (returned by buffer). You can e.g. make subview of a limited part of your ByteData if your ByteData needs to contain different types of data: https://api.dart.dev/stable/2.15.0/dart-typed_data/ByteBuffer/asUint8List.html

Related