how to use more than an api in one screen using one cubit (bloc)

51 Views Asked by At

I am trying to use multi APIs on one page using one Cubit, here is my code cubit code to fetch 2 apis

  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) {
      emit(HomeFirstSliderSuccessCase(firstSliderList: respone));
      myFirstSlider = respone;
    });
    return myFirstSlider;
  }

and here is my app route code

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

then I use the follows to call the cubit function

BlocProvider.of<HomeCubit>(context).subCat();

but unfortunately only one API works find, so how can I fetch many API in just one page in one cubit

1

There are 1 best solutions below

3
Sagar Acharya On

As you are aware the cubit is function driver development, and i see you are calling subCat() method so the emitter on api success with only emit the HomeSubCatSuccessCase with a subCatList list. So following are the solutions that you can try:

 var responses = await Future.wait([
    firstApiCall
    SecondApiCall
  ]);
// here you will get two responses : 
//1) responses[0] -first api response
//2) responses[1] -second api response
  
}

Now you can create a class with this two classes in it and emit the class.

  1. Another way is if the data is not related then you can use different states and two seprate function calls one you mentioned above and emit them and on the ui side you can have two different builder or consumer to listen them.

Update 2:

  buildWhen: (previous, current) {
   // here just check if the state is initial loading success or //error and return the value
  },
  builder: (context, state) {
    // return widget here based on BlocA's state
  }
)