我將使用比我的專案更簡單的版本,但如有必要,請隨時要求提供更多代碼。這可能更像是一個架構問題。
FooService我的應用程式中有一個暴露流的服務(介面)fooStream。我作為 bloc 類的成員擁有這項服務MyBloc。
現在 bloc 的狀態MyBlocState包含isProcessing指示 bloc 是否正在處理,并且它還包含向 UI 層fooStream公開服務版本的欄位fooStream(因此有 3 個層:service => bloc => UI)。
現在的問題是,當我想在我的 UI 中收聽此服務流時,我不得不使用一個StreamBuilder本身將被包裝在BlocBuilder. 這在大型應用程式中會變得非常混亂。那么代表fooStream集團內部狀態的最佳方式是什么?我可以只收聽 bloc 內部的流并在fooStream事件到達時向 bloc 添加一個事件嗎?在狀態將以混亂的方式更新并且無法再跟蹤狀態變化的情況下,這不是一個糟糕的副作用嗎?
示例代碼:
class FooService{
Stream fooStream;// the stream is exposed here
...
}
class MyBloc extends ... {
FooService myService = ...;//the service is used here as a member
...
}
class MyBlocState extends ... {
Stream? fooStream;//this value will hold the stream exposed from the service and it may be initialized in an init event in the bloc for example
...
}
現在在 UI 中,我必須做這件難看的事情(丑陋,因為現在我正在從 2 個地方監聽狀態,從集團和來自流,在我看來,這違背了集團作為唯一入口點的目的更改狀態并在 UI/應用程式中維護它):
Widget build(BuildContext context){
return BlocBuilder<MyBloc,MyBlocState>(
builder: (context, myBlocState) {
if(myBlocState is Loading){
return CircularProgressIndicator();
}
if(myBlocState is Error){
return ErrorWidget();
}
if(myBlocState is SomeState){
return StreamBuilder(//I need to wrap the StreamBuilder inside the BlocBuilder because the stream will be null when the app launches but then it will have a value which is fooStream when I call init in the bloc
stream: myBlocState.fooStream,
builder: (context, snapshot) {
if(snapshot.hasData){
return SomeWidget();
}
else{
return SomeOtherWidget();
}
},
);
}
},
)
}
uj5u.com熱心網友回復:
理想情況下,UI 應該只回應您的 bloc 中的狀態更改,因此我強烈建議訂閱 bloc 中的流并發出狀態以回應來自流的資料。您可以查看計時器示例以獲取管理訂閱以暫停/恢復的參考。在簡單的情況下,您可以在 bloc >=7.2.0 中使用emit.forEach或emit.onEach這意味著您不需要手動維護StreamSubscription.
您可以emit.onEach在帶有流示例的flutter bloc 中看到一個示例,并且emit.forEach看起來非常相似:
class TickerBloc extends Bloc<TickerEvent, TickerState> {
TickerBloc(Ticker ticker) : super(TickerInitial()) {
on<TickerStarted>(
(event, emit) async {
await emit.forEach<int>(
ticker.tick(),
onData: (tick) => TickerTick(tick),
);
},
transformer: restartable(),
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/326251.html
