Using Flutter Bloc for the first time? (part 1)

Manage your apps with Bloc pattern using flutter_bloc

Daniel Tavera
7 min readOct 21, 2020
Images are from Nickelodeon and designed by Daniel Tavera

If you have ever wonder how the Bloc package works and how to use all the weird widgets that exist in this package, well, we’re gonna dive into some of them and I hope to show you in a better way how Bloc behaves and how you could use it for making further scalable projects.

I know that exist more state managements like Redux, MobX, and a new one called GetX but why I decided to use Bloc in some of my own projects?

Bloc makes it easy to separate presentation from business logic, making your code fast, easy to test, and reusable. — blocLibrary

  • Simple: At a glance, it could be verbose and sometimes confused buuut when you bump into mistakes in the face and all the newbie stuff is very easy to understand 😅 👌
  • Powerful: You could split the code into multiple widgets to make it deeply readable
  • Testable: Everything can be easily tested and believe me you’re gonna code with confidence and your app will be stable

You could read more about why to use Bloc in blocLibrary, and before to start coding you have to understand how Bloc behaves and select the right events and states.

So Bloc updated its core by adding Cubit (I’m gonna write another article about Cubit) that’s easier than Bloc itself buuuut Bloc is better when you want to watch the sequence of the state changes and I made a little infographic to explain it better.

I designed an app with the avatar the last air bender animation look and feel because I really like this animation 🤓 👌 and later in another post, we’re gonna add a free avatar API for feeding this app.

In this post, we’ll set up Bloc and create the main app structure so you might clone the repo here and if you don’t want to watch the whole process for creating the structure you could go straight to the Bloc’s section, so let’s get started.

🍚 🐟 We’ll be using

  • Bloc package for state-management.
  • Logger for watching the transitions nicely
  • Flutter_svg for using svg images
  • Equatable for being able to compare objects in dart, especially the props from the events and states.

🔪 Setup

  • Add these packages to the pubspec.yaml file.
pubspec.yaml
  • I’m gonna use this folder structure but you could organize it as you want and feel more comfortable, avatarFirstPart is because I want to create another post integrating an API.
  • The next step is to create the structure app, the main.dart file just gonna use these lines so far.
  • The app.dart file is going to get a widget created by ourselves called HomeScreen
app.dart
  • Inside the screens folder, we have to create home_screen.dart, and this file will contain two widgets called Layout() and CharacterList(). We split all these widgets not only for readability but so that we can use Bloc widgets right and make it easy to test (I’ll create another post for testing this app both unit & automated tests).
home_screen.dart
  • We’re gonna use a ListView for showing the little card details in the character_list.dart file.
character_list.dart
  • If you wonder what the heck is SizeConfig().init(context) It’s just a class for making it responsive that we need to instantiate on every file we’re going to use.
size_config.dart
  • And finally, the AvatarTile widget goes like this.
avatar_tile.dart
  • The first screen that we’re going to add Bloc is finished and if everything goes right It should look like this.
Images from Nickelodeon, designed by Daniel Tavera
All the images are from Nickelodeon, designed by Daniel Tavera

🍶 Bloc section

  • Now the next step is the funny part, we have to add Bloc to the project and the first thing to do is adding BlocDelegate for watching all the state changes in our app.
  • So I’m gonna use images for this part because I think the best way to learn is writing everything ourselves instead of copy and paste by default, but if you prefer to copy here is the repo. 🤓 ✌️
main.dart
  • In the main.dart file I added Logger for printing the transitions nicely, onEvent method will show the current method triggered, onTransition will show you the state changes and onError indicates if an error has occurred in the transition and finally I only have to initialize BlocDelegate into Bloc.onbserver.
  • Now we’re going to create the bloc files for adding the event and states needed, so before writing something in these files we need to think about what would be the interaction between the user and the app and the states in Bloc.
bloc files

Event

  • On the first screen, we only are going to load the characters if the request is ok, however, we’re not using and API right now, I will go into that in greater detail in another post, so we’re going to use a boolean for this part and the event name would be AvatarLoadCharacters in the avatar_event.dart file.
avatar_event.dart

States

  • The app needs to know what is the current request state for showing us some answer in the UI in the avatar_state.dart file.
  1. AvatarInitial: It’s the initial state of the app, the user has started the app
  2. AvatarLoading: The event (AvatarLoadCharacters) has been triggered but the request is loading and we don’t yet have an answer.
  3. AvatarLoaded: The answer has arrived! 🙌 and It’s successful.
  4. AvatarFailure: The request has failed. 😢
avatar_state.dart

Avatar Bloc

  • Well in the avatar_bloc.dart we start at line 11 adding the app’s initial state AvatarInitial
  • So the next step is telling to Bloc if the event AvatarLoadCharacters is triggered then It’ll call _loadCharacters method at line 16
  • If the request is successful the state will be AvatarLoaded, otherwise, It will be AvatarFailure at line 26 to 30, easy, isn’t it? 🎉
avatar_bloc.dart
  • You might wonder why we use a Future and an if statement, well we’re not using an API, otherwise, It will be:
  • In the meantime, let’s skip this. 😉

UI Interaction with Bloc

  • The next step is to update the widgets we made previously, so at the app.dart file we only need to add BlocProvider for passing AvatarBloc to our widgets and use the event and states we created.
app.dart
  • Now we go to home_screen.dart file and here we’re going to watch our states in action. I’ll call the event in the initState because I want to load the characters as soon as the user launches the app, we only need to call the events like so.
Calling an event in Bloc (example)
  • Then as soon as the event is triggered, we use BlocBuilder to show the right widgets depending on the state request at line 25 to 33, if you change the prop event passing false instead of true, you could see how BlocBuilder will render the text There’s nothing here instead of the character list widget.
  • Remember that we created a prop called request at the avatar_event.dart file.
home_screen.dart
  • So, this is the end of part 1 and everything should work fine so the right result would be this:

🍣 🍶 Final result

  • I hope you enjoyed this tutorial and even have a better understanding of Bloc, I’m gonna write more about this, in the second part we’ll implement the details screen watching the info character, and later we’re gonna add an API, well there so much to learn. 🤓
  • This is my first post, so if you like the way I taught you please give me some claps 👏 👏, if you have any comments I would be very grateful to read your opinions, see you soon!

--

--

Daniel Tavera

I'm front-end developer and I really love all the interaction that exists both design and development