如何在不带镜像包的颤振中使用ByteData和ByteBuffer [英] How to use ByteData and ByteBuffer in flutter without mirror package

查看:77
本文介绍了如何在不带镜像包的颤振中使用ByteData和ByteBuffer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试开发一个UDP应用程序,该应用程序可以接收数据并将字节转换为不同的数据类型.

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

我下面的代码可以单独使用Dart.

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

唯一的问题是,当我尝试在Flutter应用程序中运行它时,VS代码在 d.data.buffer 处给我一个错误,提示 getter'buffer'未定义类别"List< int>".

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; 似乎无法正常运行,并且本页说飞镖镜在Flutter中被挡住了.

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?

推荐答案

d.data 的类型是普通的 List< int> ,而不是 Uint8List .一个 List 没有一个 buffer 吸气剂,因此类型系统会抱怨.

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

如果您知道该值确实是 Uint8List 或其他类型的数据,则可以在使用它之前对其进行强制转换:

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;

还请注意, Uint8List 不一定会使用其整个缓冲区.也许做类似的事情:

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

如果可能的话,并且如果 DKByteData 不支持它,那么在数据不填充缓冲区的情况下,您可能希望分配一个新的缓冲区:

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

这篇关于如何在不带镜像包的颤振中使用ByteData和ByteBuffer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆