Bloc Architecture: migrating from pragmatic and improvised authentication/db connection

Issue

I am adjusting a private project to use BLoC. I like the strict separation in BLoC but I do not know how to adjust certain parts of my project.

One of those parts is a persistent login. In my old project, I achieved this using a singleton class and before the app starts, it checks contents in [flutter_secure_storage][1], which is loaded and checked by the server. I’m not familiar with "best practice" solutions. How would I achieve this neatly?

Another part is the ‘database-connection’. My current project uses a simple interface to a REST API. This is used in combination with the authentication-singleton. I understand that the BLoC pattern requires a data layer, which should fetch data (in my case from the REST API). In my current situation, I simply get the auth data from the authentication-singleton. What is a better practice in this case?

Solution

I would use a HydratedBloc UserBloc that handles the user account. The HydratedBloc can store data it’s data about whether the user is logged in in flutter_secure_storage or whatever database you want. The BloC is then alive the whole time and saves it’s state between the user opening and closing the App.

UserBloc could take events with the logging data to make the request to the authentification service. It outputs either LoggedInState or LoggedOutState. In your Widget tree after you created your MaterialApp you can have a BlocBuilder that listens to UserBloc and returns your login page if the user isn’t logged in and your normal app otherwise.

Answered By – Christian

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *