问题
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