Flutter:尝试两次收听广播流时出现异常
Flutter: Exception while trying to listen to Broadcast stream twice
我有一个包含广播流的存储
Stream<List<DeliveryModel>> get deliveriesStream {
this._getDeliveries();
return this._controller.stream.asBroadcastStream();
}
并且有两个订阅者,一旦我开始手动收听,
var stream = this._deliveryRepo.deliveriesStream;
deliveriesSubscription = stream.listen((deliveries) {
// to do something
});
并通过 StreamBuilder
一次
@override
void initState() {
super.initState();
this.stream = this.widget.deliveriesFetcher.getDeliveriesStream();
}
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: this.stream,
builder: (context, snapshot) {
// do something
});
}
其中
@override
Stream<List<DeliveryModel>> getDeliveriesStream() {
return this._deliveryRepo.deliveriesStream;
}
如果我没理解错的话,我订阅了两次广播流,所以一切都应该没问题,但是当我第二次尝试订阅流时(通过 StreamBuilder) ,它会抛出异常:错误状态:流已被收听。有什么建议吗?
原因是每次 deliveriesStream
getter 调用时您都在创建一个新的 BroadcastStream。尝试使用这样的东西:
Stream<List<DeliveryModel>> _deliveriesStream;
Stream<List<DeliveryModel>> get deliveriesStream {
this._getDeliveries();
_deliveriesStream ??= _controller.stream.asBroadcastStream();
return _deliveriesStream;
}
我有一个包含广播流的存储
Stream<List<DeliveryModel>> get deliveriesStream {
this._getDeliveries();
return this._controller.stream.asBroadcastStream();
}
并且有两个订阅者,一旦我开始手动收听,
var stream = this._deliveryRepo.deliveriesStream;
deliveriesSubscription = stream.listen((deliveries) {
// to do something
});
并通过 StreamBuilder
一次@override
void initState() {
super.initState();
this.stream = this.widget.deliveriesFetcher.getDeliveriesStream();
}
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: this.stream,
builder: (context, snapshot) {
// do something
});
}
其中
@override
Stream<List<DeliveryModel>> getDeliveriesStream() {
return this._deliveryRepo.deliveriesStream;
}
如果我没理解错的话,我订阅了两次广播流,所以一切都应该没问题,但是当我第二次尝试订阅流时(通过 StreamBuilder) ,它会抛出异常:错误状态:流已被收听。有什么建议吗?
原因是每次 deliveriesStream
getter 调用时您都在创建一个新的 BroadcastStream。尝试使用这样的东西:
Stream<List<DeliveryModel>> _deliveriesStream;
Stream<List<DeliveryModel>> get deliveriesStream {
this._getDeliveries();
_deliveriesStream ??= _controller.stream.asBroadcastStream();
return _deliveriesStream;
}