在 flutter dart 中将列表组合在一个列表中

combine lists in one list in flutter dart

我有 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大小不一致。所以我想将所有这些即将到来的数据合并到一个列表中。

这是我正在尝试使用的代码,由于数据未合并,因此无法正常工作。


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



  }

如何将所有传入的数据合并到一个大列表中并存储起来供以后操作。

试试下面的代码

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]

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

如果我没记错connection!.input就是一个Stream.

如果是这样,那么您的问题似乎不是您所说的列表,而是 Streams。

由于您正在收听 Stream:

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

并且您想更改、修改或处理来自 Stream 的即将到来的数据,那么您可能想使用一些原生的 StreamAPI.

在这种特殊情况下,您想减少所有即将发生的事件(Uint8List 的列表)并处理成单个输出(包含所有数据的单个 Uint8List),那么您可以使用 Stream<T>.reduce 其中 returns 一个 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 documentationStream,它是完整的和有指导意义的。