I have a class called DataCollectionPage where I have the following function in the initState function:
void establishConnection (){
BluetoothConnection.toAddress(widget.server!.address).then((connection) {
Utils.showSnackBar2("Successfully connected to your device");
this.connection = connection;
setState(() {
isConnecting = false;
isDisconnecting = false;
});
this.connection!.input!.listen(_onDataReceived).onDone(() {
if (isDisconnecting) {
Utils.showSnackBar2("Device Disconnected!!");
} else {
Utils.showSnackBar2("Device Disconnected!!");
}
if (mounted) {
setState(() {});
}
});
}).catchError((error) {Utils.showSnackBar("Connection failed, please try again later");
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const BluetoothConnectionTask()),
);
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Error occurred while connecting'),
content: const Text(
"Connection failed. Please Try connecting to your device again"),
actions: <Widget>[
TextButton(
child: const Text("Close",style: TextStyle(color: Colors.black),),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
});
}
Then, in the same class, I have another function (startDataCollection) that looks like this:
void startDataCollection() async {
startFlag = startFlag.trim();
try {
List<int> list = startFlag.codeUnits;
Uint8List bytes = Uint8List.fromList(list);
connection!.output.add(bytes);
await connection!.output.allSent;
} catch (e) {
print(e);
}
}
At this point, there is no issue. However when I tried calling startDataCollection function from another screen (DataCollectionTimer Class), I got an error that
Null check operator used on a null value
which was referring to "connection" from the startDataCollection function.
Basically, I established a bluetooth connection with some hardware when I called the function establishConnection for the first time, and when I called it from the class DataCollectionTimer, it was still connected, but for some reason the connection var was empty when I called it from the DataCollectionPage class.
How can I use the function startDataCollection from another screen correctly?
If you need any more elaboration please let me know and thank you in advance.
2
Answers
Update:
I simple solved the problem by changing Bluetooth connection to global
Old:
New:
Please ensure:
BluetoothConnection.toAddress(widget.server!.address).then
before doing anything with theconnection
valueconnection
received fromBluetoothConnection.toAddress(widget.server!.address).then((connection)
is not null