Issue
I have 100 sample of data coming from microcontroller via bluetooth in a form of Uint8List continuously. The data is coming through bluetooth buffer and I am using flutter bluetooth serial package to receive data via bluetooth. The data is arriving in this form:
[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)
The size of the List containing the Uint is not consistent. So I want to combine all these coming data in one List.
This is the code I am trying to use which is not working as the data is not being combined.
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);
}
How can I combine all the coming data in one big list and store it for later operations.
Solution
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
If I'm not wrong, connection!.input
is a Stream
.
If so, then seems your problem isn't about lists as you said, but about Stream
s.
Since you are listening to a Stream
:
connection!.input!.listen(_onDataReceived).onDone(...);
And you want to alter, modify or process the upcoming data from a Stream
then you probably want to use some of the native Stream
API.
In this particular case, you want to reduce all upcoming events (list of Uint8List
) and process into a single output (a single Uint8List
containing all data), then you can use Stream<T>.reduce
which returns a Future<T>
that resolves when there are no more upcoming events (Stream
did emit the done event).
You don't even need to listen since you want just to process the single output not each event individually:
final Uint8List mergedData = await connection!.input!.reduce((previous, current) => Uint8List.fromList([...previous, ...current]));
Take a look at this DartPad snippet to see a full example.
To see full API, check out the official Dart documentation for Stream
s, it's complete and didactic.
Answered By - lakscastro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.