I'm writing a program that needs to communicate with my bluetooth module.
I have singleton BluetoothController that has a future function which is supposed to send request to bluetooth and listen for and return a response, which comes through a broadcast stream. Now, the problem I'm having is that when I call the function from UI (gets called by a FutureBuilder) nothing happens, or rather FutureBuilder snapshot.hasData is false, so basically the future is waiting infinitely to finish. What I really don't understand is that the program seems to stop at return line of the BluetoothController function. And the even weirder thing is that if it's called again (via refresh for FutureBuilder) it works and prints 'done' when the second call to function goes inside 'await for' (after 'sendMessageToBluetooth', but before 'print(configData.toString())'). I was hoping someone can make sense of this because I haven't a clue what's going on here.
FutureBuilder future function in my main page. Gets called on page load (and doesn't work), and every 10 seconds (for testing):
Future<bool> getConfigData() async {
ConfigData? configData = await bluetoothController.getConfigData();
print('done'); // doesn't execute
...
}
Bluetooth controller (get's called from above code):
Future<ConfigData?> getConfigData() async {
var stream = listenForResponses(); // stream which yields strings when they arrive from bluetooth
sendMessageToBluetooth(getConfigDataRequest); // sends request to bluetooth module
await for (String data in stream) {
// 'done' from the other function gets printed around the time the second call to this function gets to this line
ConfigData configData = ConfigData.fromJson(jsonDecode(data)); // decodes json data
print(configData.toString()); // prints correct data, which means stream is yielding data
return configData; // this is where the program stops
}
return null; // linter wants this here
}
My understanding of what's happening is that the first call to the function returns a value only after the function is called again.
It's worth mentioning that using configData = await stream.first in the function seems to block it at that line, it doesn't work, even though I'm sure the stream yielded a value.