flutter?Bloc?add兩次只響應一次問題解析
問題描述
連續(xù)調(diào)用兩次addEvent,結(jié)果最終只能響應一次,第二次事件無法響應。
@override Stream<SomeState> mapEventToState(SomeEvent event) async*{ if(event is InCreaseEvent){ state.num ++; yield state; } }
someBloc.add(InCreaseEvent()); someBloc.add(InCreaseEvent());
原因分析
bloc 繼承于 cubit , 查看 cubit 源碼得知,狀態(tài)更新時做了判斷,如果接收到的 newState 與 currentState 為同一個對象,則直接 return,不響應本次狀態(tài)變更。
處理方式
1. State實現(xiàn)copyWith()方法每個State類都要有copy()方法,用于產(chǎn)生state對象的副本;每次編輯 state 的字段內(nèi)容,然后 yield 副本,保證每次 yield 的都是新的對象。
class SomeBloc extends Bloc<SomeEvent, SomeState>{ SomeState _currentState; SomeBloc(SomeState initialState) : super(initialState){ _currentState = initialState; } @override Stream<SomeState> mapEventToState(SomeEvent event) async*{ if(event is InCreaseEvent){ _currentState.num ++; //每次 yield 新對象 yield _currentState.copyWith(); } } } class SomeState{ int num; SomeState(this.num); ///新加 copyWith 方法用于生成副本 SomeState copyWith(){ return SomeState(num); } } abstract class SomeEvent{} class InCreaseEvent extends SomeEvent{}
2.使用Equatable state繼承Equatable重寫get方法
以上就是flutter Bloc add兩次只響應一次問題解析的詳細內(nèi)容,更多關于flutter Bloc add兩次響應一次的資料請關注腳本之家其它相關文章!
相關文章
Android_RecyclerView實現(xiàn)上下滾動廣告條實例(帶圖片)
本篇文章主要介紹了Android_RecyclerView實現(xiàn)上下滾動廣告條實例(帶圖片),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06android LinearLayout和RelativeLayout組合實現(xiàn)精確布局方法介紹
用android LinearLayout和RelativeLayout實現(xiàn)精確布局此方法適合很適合新人看2012-11-11APP添加CNZZ統(tǒng)計插件教程 Android版添加phonegap
這篇文章主要介紹了APP添加CNZZ統(tǒng)計插件教程,Android版添加phonegap,感興趣的小伙伴們可以參考一下2015-12-12