Flutter, using a bloc in a bloc

家住魔仙堡 提交于 2021-01-28 21:22:22

问题


I have two BLoCs.

  • EstateBloc
  • EstateTryBloc

My Application basically gets estates from an API and displays them in a similar fashion

Now I wanted to add a sort functionality, but I could only access the List of Estates via a specific state.

    if(currentState is PostLoadedState){{
    print(currentState.estates);
    }

I wanted to make the List of estates available for whichever bloc, that needed that list.

What I did was, I created the EstateTryBloc, which basically contains the List of estates as a state.

class EstateTryBloc extends Bloc<EstateTryEvent, List<Estate>> {
  @override
  List<Estate> get initialState => [];

  @override
  Stream<List<Estate>> mapEventToState(
    EstateTryEvent event,
  ) async* {


    final currentState = state;
    if(event is AddToEstateList){
      final estates = await FetchFromEitherSource(currentState.length, 20)
          .getDataFromEitherSource();
      yield currentState + estates;
    }
  }
}

As I print the state inside the bloc I get the List of estates but I dont know how I would use that List in a different bloc.

print(EstateTryBloc().state);

simply shows the initialState.

I am open for every kind of answer, feel free to tell me if a different approach would be better.


回答1:


When you do print(EstateTryBloc().state); you are creating a new instance of EstateTryBloc() that's why you always see the initialState instead of the current state.

For that to work, you must access the reference for the instance that you want to get the states of. Something like:

final EstateTryBloc bloc = EstateTryBloc();

// Use the bloc wherever you want

print(bloc.state);



回答2:


Right now the recommended way to share data between blocs is to inject one bloc into another and listen for state changes. So in your case it would be something like this:

class EstateTryBloc extends Bloc<EstateTryEvent, List<Estate>> {
  final StreamSubscription _subscription;

  EstateTryBloc(EstateBloc estateBloc) {
    _subscription = estateBloc.listen((PostState state) {
      if (state is PostLoadedState) {
        print(state.estates);
      }
    });
  }

  @override
  Future<Function> close() {
    _subscription.cancel();
    return super.close();
  }
}



回答3:


To be honest I overcomplicated things a little bit and did not recognize the real problem. It was that I accidently created a new instance of EstateBloc() whenever I pressed on the sort button. Anyways, thanks for your contribution guys!



来源:https://stackoverflow.com/questions/60002199/flutter-using-a-bloc-in-a-bloc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!