Flutter Tips: Generic Data Fetching Using Bloc

Mario Gunawan
Flutter Tips
Published in
2 min readOct 31, 2022

--

This article is intended for people that’s already familiar with flutter and bloc

Recently, I’ve stumbled upon a problem where I would like to fetch data using bloc in flutter. I could create several bloc, each with their own http client, but there would be a lot of code duplications if we use that approach. So I used a more generic and simple approach to this problem.

Here is the code ☕️

Here is the bloc & events

You might notice that there’s an onCreate() method on the code. It’s used to add the fetching data event when the bloc is initiated. If you don’t add a fetching data event during bloc’s instantiation, you will need to call it in your flutter initState code. So… yeah, I think this approach is simpler (and better because of more stateless component)

Here’s the states that was mentioned above

There’s a lot of <T> sign there, and that’s called generics. Basically, it allows us to reuse the same logic if we have different data types. In this example, I can reuse the same Bloc logic when I fetch, let’s say, a voucher, and when I fetch a list of vouchers. This will reduce code duplication and allow us to remember less things.

In our widgets, we can use our bloc like this:

⚠️ Be careful to not use any generic type indicator in both the blocbuilder or the blocprovider class, for example doing this will not match any state

// this
if ( state is DataFetchLoaded<int> )
// this also won't work
BlocProvider<DataFetchBloc<int>, DataFetchState> ( ... )

even though the state is integer.

That’s why actually we can remove the generic type indicators and it still will work. But I prefer to keep it this way to indicate that this class can be used for many data types fetched from server.

If your state is not primitive (for example your fetched data is a list of pokemons) then use the as syntax instead of generic type matching:

if(state is DataFetchLoaded) {
final listOfPokemons = state.data as List<Pokemon>;
}

That’s it. Hope this helps!

Further reading:

Thanks to the article that inspired this article.

--

--

Mario Gunawan
Flutter Tips

I'm a passionate mobile / web developer. Writing articles about software development, mainly about flutter and react.