How to show two state data in single UI Using Bloc

51 Views Asked by At

I have two APIs, and the second API depends on the first, i mean first need to fetch data from the first API and then take the ID from it need to request 2nd API and show both APIs Data on UI how to manage it with bloc?

2

There are 2 best solutions below

0
On

Start by developing two BLoCs, bloc1 and bloc2, each of which will handle the logic for a single API, in order to simplify your solution. To add both BLoCs to the widget tree, use MultiBlocProvider at the beginning of your target page. Make sure bloc1 contains data from the initial API in a success state, such as Bloc1Success. When bloc1 emits a Bloc1Success state, use a BlocListener for bloc1 in your UI to start the event for the second API fetch from bloc2. Within bloc2, make the second API call and emit the your bloc2 states. When bloc2 emits a Bloc2Success state, use a BlocBuilder for bloc2 in the UI to retrieve data from bloc1 and bloc2.

2
On

Note: I am assuming that your BLoc is same for both API call methods

  1. If you want to show list of first API which is API calling then you can listen the first state using BLocListner and save that list locally and show them in UI.
class Demo extends StatefulWidget {
  const Demo({super.key});

  @override
  State<Demo> createState() => _DemoState();
}

class _DemoState extends State<Demo> {

  List api1SuccessList = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: BlocConsumer<CurrentBetsCubit, CurrentBetsState>(
        listener: (context, state) {
          if(state is Api1ResponseFeatchSuccessState){
            api1SuccessList = (list from yout state or Bloc)
          }
        },
        builder: (context, state) {
          if(state is Api1ResponseFeatchSuccessState){
            // Render Your UI for first API
            return ListView.builder(
              itemCount: api1SuccessList.length,
              itemBuilder: (context, index) {
              
                // Make request for the 2nd API with specific index and specific id;
                
                /// Call your BLoc method here and pass require argument like id
                context.read<YourBloc>().secondApiCall(firstApiResponseSpecificId);
                
            },);
          }else if(state is Api2ResponseFeatchSuccessState){
            // Render your UI for second API
          }else{
            const SizedBox.shrink();
          }
        },
      ),
    );
  }
}