简体   繁体   中英

Flutter, using a bloc in a bloc

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.

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();
  }
}

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);

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM