How to use ByteData and ByteBuffer in flutter without mirror package

6,610

The type of d.data is plain List<int>, not Uint8List. A List does not have a buffer getter, so the type system complains.

If you know that the value is indeed Uint8List or other typed-data, you can cast it before using it:

ByteBuffer buffer = (d.data as Uint8List).buffer;

Also be aware that a Uint8List doesn't necessarily use its entire buffer. Maybe do something like:

Uint8List bytes = d.data;
DKByteData data = new DKByteData(bytes.buffer, bytes.offsetInBytes, bytes.lengthInBytes);

if possible, and if DKByteData doesn't support that, you might want to allocate a new buffer in the case where the data doesn't fill the buffer:

Uint8List bytes = d.data;
if (bytes.lengthInBytes != bytes.buffer.lengthInBytes) {
  bytes = Uint8List.fromList(bytes);
}
DKByteData data = new DKByteData(bytes.buffer);
Share:
6,610
iProgram
Author by

iProgram

Updated on December 06, 2022

Comments

  • iProgram
    iProgram over 1 year

    I am trying to develop a UDP application that receives data and converts the bytes into different data types.

    I have the code below that works when using Dart on its own.

    import 'dart:io';
    import 'dart:typed_data';
    import 'dart:mirror';
    
    RawDatagramSocket.bind(InternetAddress.ANY_IP_V4, 20777).then((RawDatagramSocket socket){
      socket.listen((RawSocketEvent e){
        Datagram d = socket.receive();
        if (d == null) return;
        ByteBuffer buffer = d.data.buffer;
        DKByteData data = new DKByteData(buffer);
        exit(0);
      });
    });
    

    The only issue is when I try to run it inside my Flutter application, VS code gives me an error at d.data.buffer saying The getter 'buffer' isn't defined for the class 'List<int>'.

    import dart:mirror; does not seem to work in flutter and this page says that dart mirrors is blocked in Flutter.

    As I cannot import dart mirror in order to get a Bytebuffer from a Datagram socket, how else am I able to do this?

  • iProgram
    iProgram over 5 years
    If I were to do DKByteData data = DKByteData(Uint8List.fromList(d.data).buffer);, would that guarantee that I get all the bytes as I'm simply skipping your check and getting the UInt8List.fromList straight away? This is what I found out before you posted. You have more useful information then what I found though. I just found out 'how'. You have told me 'why' and some warnings too.
  • lrn
    lrn over 5 years
    Yes, that would always get you all the bytes of the original list. It will copy the bytes to a new buffer, even when the original buffer would have sufficed, so you will get an extra overhead.