I am using the connectivity
plugin in my flutter to check for the connection status, but occasionally hitting the error PlatForm Exception(No active stream to cancel, null)
even though i have handled the null case. I have subscribed to the stream in initState
and cancelled the subscription in dispose
state
my code looks something like this.
StreamSubscription streamConnectionStatus;
------------
//remaining code
------------
@override
void initState() {
getConnectionStatus();
}
getConnectionStatus() async {
streamConnectionStatus = new Connectivity()
.onConnectivityChanged
.listen((ConnectivityResult result) {
// Got a new connectivity status!
if (result == ConnectivityResult.mobile ||
result == ConnectivityResult.wifi) {
setState(() {
boolHasConnection = true;
});
} else {
setState(() {
boolHasConnection = false;
});
}
});
@override
void dispose() {
try {
streamConnectionStatus?.cancel();
} catch (exception, stackTrace) {
print(exception.toString());
updateError(exception.toString(), stackTrace);
} finally {
super.dispose();
}
}
this is actually driving me crazy but i am guessing i am missing something or do i have to change the code.
Many thanks, Mahi
I encountered a similar issue. This is what helped me.
I had subscribed the stream exposed by connectivity plugin in different widgets in the same widget tree. I removed the subscription from child widgets and retained the subscription only in the parent and passed on the connection status to the children from parent.
By doing so my code got more cleaner and the stream subscription was maintained / disposed only at one place. Then I didn't encounter this issue any more.