Android Studio 在flutter dart中将列表合并为一个列表

q8l4jmvw  于 2023-01-31  发布在  Android
关注(0)|答案(3)|浏览(158)

我有100个通过蓝牙以Uint8List形式连续从微控制器传来的数据样本。数据通过蓝牙缓冲区传来,我使用flutter蓝牙串行包通过蓝牙接收数据。数据以以下形式到达:

[115, 43, 48, 46, 56, 54, 101, 0, 0, 115]
[43, 49, 46, 55, 49, 101, 0, 0, 115, 43]
[0, 0, 115, 43, 51, 46, 53, 57, 101, 0, 0, 115, 43, 51, 46] ... ect

(note that this is just an example of the result and the completed result is about 80 lists of Uint all coming to the same var which is data)

包含Uint的List的大小不一致。所以我想把所有这些数据合并到一个List中。
这是我试图使用的代码,由于数据没有被合并,因此无法正常工作。

connection!.input!.listen(_onDataReceived).onDone(() {
        if (isDisconnecting) {
          print('Disconnecting locally!');
        } else {
          print('Disconnected remotely!');
        }
        if (this.mounted) {
          setState(() {});
        }
      }

 Future<void> _onDataReceived(  Uint8List data ) async {

    List newLst =[];
    newLst.add(data);
    int i = 0;
    Queue stack = new Queue();
    stack.addAll(newLst);

    print(data);
    print(stack);


  }

我如何将所有即将到来的数据合并到一个大列表中,并将其存储以供以后操作。

qyswt5oh

qyswt5oh1#

请注意,这只是结果的一个示例,完整的结果大约是80个Uint列表,所有这些列表都属于同一个var,即data

如果我没猜错的话connection!.input就是Stream

如果是这样,那么你的问题似乎不是你所说的列表,而是Stream s。
由于您正在收听Stream

connection!.input!.listen(_onDataReceived).onDone(...);

如果您希望**更改、修改或处理来自Stream的即将到来的数据,**那么您可能希望使用一些原生Stream API。
在这个特定的例子中,你想减少所有即将发生的事件(Uint8List列表)并处理成一个输出(一个包含所有数据的Uint8List),那么你可以使用Stream<T>.reduce,它返回一个Future<T>,当没有更多即将发生的事件时(Stream确实发出了 done 事件),它会解析。
您甚至不需要侦听,因为您只想处理单个输出,而不是单独处理每个事件:

final Uint8List mergedData = await connection!.input!.reduce((previous, current) => Uint8List.fromList([...previous, ...current]));

a look at this DartPad snippet为例查看完整示例。
要查看完整的API,请查看official Dart documentation for Stream s,它是完整的和教学性的。

shyt4zoc

shyt4zoc2#

尝试以下代码

void main() {
  List l1 = [115, 43, 48, 46, 56, 54, 101, 0, 0, 115];
  List l2 = [43, 49, 46, 55, 49, 101, 0, 0, 115, 43];
  List l3 = [0, 0, 115, 43, 51, 46, 53, 57, 101, 0, 0, 115, 43, 51, 46];

  l1.addAll(l2 + l3);
  print(l1);
}

输出:

[115, 43, 48, 46, 56, 54, 101, 0, 0, 115, 43, 49, 46, 55, 49, 101, 0, 0, 115, 43, 0, 0, 115, 43, 51, 46, 53, 57, 101, 0, 0, 115, 43, 51, 46]
twh00eeo

twh00eeo3#

检查字节构建器:

var combinedList = BytesBuilder();
  var l1 = Uint8List(5);
  var l2 = Uint8List(5);
  combinedList.add(l1);
  combinedList.add(l2);
  var combinedList_to_Uint8List = combinedList.toBytes()

相关问题