Search code examples
flutterdartuint

Replacement of ArrayBuffer and DataView in Flutter


I'm very new to core dart and I am having trouble in converting a piece of javascript code to dart. Please help me convert the following JS code to DART:

            password = "1234"
            value = [0x00, 0x01, 0x00, 0x00, 0x00, 0x00];

            arrPassword = new ArrayBuffer(2); // an Int16 takes 2 bytes
            viewPassword = new DataView(arrPassword);
            viewPassword.setUint16(0, password, true); // byteOffset = 0; litteEndian = true
            var uint8ViewPassword = new Uint8Array(arrPassword);
            var mergedArray = new Uint8Array(value.length + uint8ViewPassword.length);
            mergedArray.set(value);
            mergedArray.set(uint8ViewPassword, value.length);

There is no ArrayBuffer or DataView in Dart and I am unsure what are their replacements .


Solution

  • You can start with this and then change it to your needs:

      const password = "1234";
      const value = [0x00, 0x01, 0x00, 0x00, 0x00, 0x00];
    
      final passwordBytes = encodeUtf16le(password);
    
      final mergedArray = Uint8List.fromList([
        ...value,
        ...Uint8List.fromList(passwordBytes),
      ]);
    

    encodeUtf16le you can find here

    also, it may be helpful:

    DataView(js) -> ByteData(dart)
    Uint8Array(js) -> Uint8List(dart)