Try to override dispose()
method of the state and cancel subscription within it. To do that you need to save subscription in a variable:
StreamSubscription _subscription;
@override
void initState() {
super.initState();
_subscription = widget.connection.input.listen(_onDataReceived, onDone: () {
...
});
}
override
void dispose() {
_subscription.cancel();
super.dispose();
}
Edit
If you need to subscribe to the connection.input
multiple times across the app - you can transform it to broacast stream and subscribe for it. It should help. Like this:
final broadcastInput = connection.input.asBroadcastStream();
But if you need to use connection only in this widget I would recommend you to keep it inside state (not widget) and close it on dispose. It would be better lifecycle control solution.
BluetoothConnection _connection;
@override
void initState() {
super.initState();
_initConnection();
}
Future<void> _initConnection() async {
_connection = await BluetoothConnection.toAddress(address);
/// Here you can subscribe for _connection.input
...
}
@override
void dispose() {
connection;
super.dispose();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…