0

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.

2 Answers 2

3

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());
  }
0

You could do this with in the initState of whatever the first page is that your app loads.

class TestPage extends StatefulWidget {
  @override
  State<TestPage> createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> {
  late MarketBloc marketBloc;

  @override
  void initState() {
    super.initState();
    marketBloc = BlocProvider.of<MarketBloc>(context);
    marketBloc.add(MarketSelectEvent());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: BlocBuilder<MarketBloc, MarketListState>(
          builder: (context, state) {
            if (state is MarketLoading) {
              return Text('loading...');
            }
            if (state is MarketDataFetched) {
              return ...your UI that contains data from API call
            }
          },
        ),
      ),
    );
  }
}


Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.