User Cubit
Learn how to use Cubits to manage user authentication and state in a Flutter app using the repository pattern and fluuter_bloc library.
We'll cover the following...
We will begin by implementing the UserCubit
, which manages the user state. The application listens to this state, showing the login screen if the user is logged out and displaying the home screen if the user is logged in.
Cubits, like Blocs, have states. We generate these states in the same way as Bloc states. The only difference between Cubits and Blocs is that instead of listening to event streams, we define functions that can be called within our code.
UserState
The UserCubit
will emit several states, all of which extend the UserState
abstract class.
import 'package:ecommerce/models/user.dart';abstract class UserState {}class UserInitial extends UserState {}class UserSignedIn extends UserState {final User user;UserSignedIn(this.user);}class UserSignedOut extends UserState {}class UserLoading extends UserState {}class UserError extends UserState {final String message;UserError(this.message);}
Here’s what the code above does:
Lines 1–3: Import the
User
model and define an abstract classUserState
.Lines 5: Define the subclass
UserInitial
that represents the initial state of theUserCubit
.Lines 7–11: Define the subclass
UserSignedIn
that represents the state emitted when the user successfully signs in. It includes aUser
object to represent the signed-in user.Line 13: Define the subclass
UserSignedOut
that represents the state emitted when the user logs out of the app.Line 15: Define the subclass
UserLoading
that represents the state emitted while the authentication service is working on authenticating the user.Lines 17–21: Define the subclass
UserError
that represents the state emitted when there is an error signing in or creating new users. It includes aString
message to provide more ...