using mutli methods in one cubit with different emit in cubit (bloc)

35 Views Asked by At

I am building homepage that holds one cubit as following

cubit: class HomeCubit extends Cubit<HomeState> {
  final HomeRepository homeRepository;

  HomeCubit(
    this.homeRepository,
  ) : super(HomeInitial());

  List<SubCatModal> mySubCat = [];
  List<SubCatModal> subCat() {
    emit(HomeLoaded());
    homeRepository.getSubCatRepository().then((respone) {
      emit(HomeSubCatSuccessCase(subCatList: respone));
      mySubCat = respone;
    });
    return mySubCat;
  }

  List<FirstSlideModal> myFirstSlider = [];
  List<FirstSlideModal> sliderListCubit() {
    emit(HomeLoaded());
    homeRepository.getFirstSliderRepository().then((respone) {
      try {
        emit(HomeFirstSliderSuccessCase(firstSliderList: respone));
      } catch (e) {
        emit(HomeErrorCase(message: respone));
      }
      myFirstSlider = respone;
    });
    return myFirstSlider;
  }
}

and i call the cubit and 2 methods as follwing

case Routes.homeScreen:
        return MaterialPageRoute(
          builder: (_) => BlocProvider(
            create: (BuildContext context) =>
                HomeCubit(HomeRepository(homeApi: HomeApi()))..subCat()
              ..sliderListCubit(),,
            child: const Homepage(),
          ),
        );

and here is my code in the screen

 BlocBuilder<HomeCubit, HomeState>(
        builder: (context, state) {
          if (state is HomeSubCatSuccessCase) {}else{text("loding")}


 BlocBuilder<HomeCubit, HomeState>(
        builder: (context, state) {
          if (state is HomeFirstSliderSuccessCase) {}else{text("loding")}

everything works fine so far, but the problem here is when i emit HomeFirstSliderSuccessCase the blocbulider of HomeSubCatSuccessCase goes to else "loding" so the 2 emits reflicts with eachother, so how to make them works perfeclty speartly

1

There are 1 best solutions below

0
puelo On

I suggest you either split this up into two Cubits or merge those two functions into a larger data object to emit in a singular event.

Both BlocBuilder get notified of any state change you emit from HomeCubit, and thus both will execute builder again if you emit HomeSubCatSuccessCase. Leading to the issue you describe.

You could theoretically try to prevent a rebuild of one of the builders by leveraging buildWhen, but i would not recommend it.