Bloc: Question regarding API request

Created on 22 Jun 2020  路  9Comments  路  Source: felangel/bloc

This is another Question regarding sending API request from bloc.

return BlocProvider(
      create: (context) {
        NetworkCallBloc _networkingBloc = NetworkCallBloc();
        **_networkingBloc.add(FetchDataEvent());**
        return _networkingBloc;
      }

As you can see here, I am calling api in creation of the bloc, which is by using FetchDataEvent() function, is it okay to use it? or is there any better alternative for putting a code to call api request?

question

Most helpful comment

@felangel Thanks, I got my all the answers.

All 9 comments

Hi @jaydangar 馃憢

A more concise way would be:

BlocProvider(
      create: (_) => NetworkCallBloc()..add(FetchDataEvent())
)

Hi @jaydangar 馃憢
Thanks for opening an issue!

This approach is totally fine but there are a couple of things to note:

  1. By default blocs are creating lazily so the create method won't actually get executed until the bloc is looked up either by BlocProvider.of<NetworkCallBloc>(context) or by a BlocBuilder/BlocListener/BlocConsumer. If you want create to be executed immediately, set lazy to false like:
BlocProvider(
    lazy: false,
    create: (_) => NetworkCallBloc()..add(FetchDataEvent())
    child: ...
)
  1. As @rollyperes mentioned you can make it more concise by chaining the add 馃憤

Hope that helps!

Closing for now but feel free to comment with any additional questions and I'm happy to continue the conversation 馃槃

Great didn't thought of it, thanks. And is it good practice to do api call within bloc creation???

Great @felangel @RollyPeres and thanks for the response.

@jaydangar typically your bloc should be named after a feature or use-case and depend on one or more repositories. The repositories should consume one or more data-providers or API clients. You can read more about this in the architecture docs.

@felangel , I didn't understand the presentation layer part. It says AppStarted event will be triggered when I start my application, but what if I need to fetch data on start of the page?? can you kindly elaborate on this?

And is it good practice to do api call within bloc creation???

Bloc works by adding events to it and these events can be translated into API calls and/or bloc state/s.
Bloc is not opinionated about what you should do as a result of an event hitting bloc.

@jaydangar same thing applies to page loads. You can have a feature bloc like FavoritesBloc and add an event like FavoritesStarted when the page is created (within the create of the BlocProvider).

@felangel Thanks, I got my all the answers.

Was this page helpful?
0 / 5 - 0 ratings