Ad

Calling Async Event In Flutter_bloc

- 1 answer

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.

Ad

Answer

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());
  }
Ad
source: stackoverflow.com
Ad