日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

flutter?Bloc?add兩次只響應一次問題解析_Android

作者:李小轟_Rex ? 更新時間: 2022-12-12 編程語言

問題描述

連續調用兩次addEvent,結果最終只能響應一次,第二次事件無法響應。

@override
  Stream<SomeState> mapEventToState(SomeEvent event) async*{
    if(event is InCreaseEvent){
      state.num ++;
      yield state;
    }
  }
someBloc.add(InCreaseEvent());
someBloc.add(InCreaseEvent());

原因分析

bloc 繼承于 cubit , 查看 cubit 源碼得知,狀態更新時做了判斷,如果接收到的 newState 與 currentState 為同一個對象,則直接 return,不響應本次狀態變更。

處理方式

1. State實現copyWith()方法每個State類都要有copy()方法,用于產生state對象的副本;每次編輯 state 的字段內容,然后 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方法

原文鏈接:https://juejin.cn/post/7006213343996280868

欄目分類
最近更新