How to use ByteData and ByteBuffer in flutter without mirror package

浪子不回头ぞ 提交于 2021-01-28 23:00:59

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/51801051/how-to-use-bytedata-and-bytebuffer-in-flutter-without-mirror-package

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!