Part 6: State management with Cubit

Firebase

In this basic demo series, I introduced and demonstrated parts such as UI, basic state management, navigation and data passing, and networking. There's one more part I want to introduce, and that is managing state with Bloc Cubit.

I.Why do we need to manage state in a more advanced way?

Clearly, on the HomeScreen, we only used basic setState, and the UI was responsive enough. So why do we need to manage state differently?

Looking at the state management on the HomeScreen, we can see: the entire logic and UI are all in the same class, and this structure is clearly not clean. Using setState alone, we can build any application, but the logic for many applications is often complex. Therefore, if we can separate logic and presentation, the structure will be much cleaner. Bloc Cubit will help us achieve that. All data processing logic is pushed to Cubit to handle and update the state. The HomeScreen only needs to draw the corresponding UI based on the state.

II.Refactor the HomeScreen

Add the packages to pubspec.yaml: flutter_bloc and bloc

Add lib https://pub.dev/packages/flutter_blochttps://pub.dev/packages/bloc 

Proceed to separate classes according to the model above

1.State

HomeState represents the data as a class containing the states of the home screen. All states of the home screen will be added here.

2.Cubit

HomeCubit will contain all the logic of the HomeScreen. To transform the logic of fetching the list of questions to Cubit, we have:

3.UI

The data and logic for the UI are sufficient, now let's complete the update for the HomeScreen to establish the connection

We have:

III.Summary

So, all classes have been completely separated: HomeScreen only contains UI. HomeCubit handles the logic and updates HomeState. However, there's a small thing that I'm not satisfied with yet, which is the copyWith function in HomeState. For larger applications with many states, the copyWith function can become very large, and developers may notice a lot of duplicated code. But rest assured, there are ways to handle this, and that's by automatically generating code with https://pub.dev/packages/freezed, which I introduced in the Base Flutter series.

You've seen a practical implementation of a small screen throughout this series. For the remaining parts, I leave it to you to continue implementing to complete the application. In this series, I focused on addressing the main issues enough for newbies to understand and continue developing on their own.

Thank you all.