Calling async event in flutter_bloc

Issue

I am trying to fetch data from API as soon as the flutter app loads but I am unable to achieve so

class MarketBloc extends Bloc<MarketListEvent, MarketListState> {
  MarketBloc() : super(MarketLoading()) {
    on<MarketSelectEvent>((event, emit) async {
      emit(MarketLoading());
      final data = await ApiCall().getData(event.value!);
      globalData = data;
      emit(MarketDataFetched(marDat: globalData.data, dealType: event.value));
    });

    
  }
}

I have called MarketLoading state as the initial state and I want to call MarketSelectEvent just after that but in the current code, action is required to do so and i want to achieve it without any action.

Solution

You have 2 options:

add an event from the UI as soon you instantiate the MarketBloc

  MarketBloc()..add(MarketSelectEvent())

add an event in the initialization code

  MarketBloc() : super(MarketLoading()) {  
    add(MarketSelectEvent());
  }

Answered By – Michael m

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.