Handle a login / signup flow can cause some serious headaches with Flutter, using BLoC can make your life much easier and clarify the whole process, so let’s dive in this tuto… journey!
First things first, since this isn’t a basic tutorial we will take for granted the knowledge of the routes and we’ve also included a little bit of “validation” with formz package to create reusable models; it’s not the purpose of this tutorial to show how this will work, you will see this in the next tutorial. For the login part we’ve also used, for tutorial purposes, a subset of BLoC (Cubit) so you will see the difference between those two.
Before we dive in let’s add to our pubspec.yaml the necessary packages:
Adding the equatable package will only make your life easier but if you want to compare instances of classes “manually” you just need to override “==” and the hashCode.
Let’s start with a class that will contain the status of the form and all the fields states:
But how can we connect the Cubit to our UI? Here that comes to the rescue the BlocProvider, a widget which provides a bloc to its children using: BlocProvider.of<LoginCubit>(context)
Since now seems all at his own place it’s time to settle down the last piece of our puzzle, the whole UI
To react to the new states emitted by out Cubit we need to wrap our form in a BlocConsumer; now we’ll have exposed a listener and a builder.
Here we will listen for state changes and, for example, show an error in response of an API call or perform Navigation.
Here we will show the ui reacting to state changes of our Cubit.
Our UI consists of a Column with 5 children but we’ll just show 2 widgets to be brief:
Both widgets are wrapped in a BlocBuilder that’s responsible to rebuild these widgets only when the cubit emits new states for their respective evaluated properties, so for example, if the user doesn’t type anything in the email field, _EmailInputField won’t ever be rebuilt.
The button instead, if all fields are validated, will invoke logInWithCredentials() function that will emit a new status (failure or success) based on the API response.
Part 1 of our journey containing the login flow comes to an end, you can reach this tutorial’s code inside this GitHub repository. See you the next time with the Sign Up Flow!