CodeX
Published in

CodeX

Flutter User Authentication Part 2: Storing Users With The Cubit

Photo by Michael Dziedzic on Unsplash

What is a Cubit?

Creating Our Cubit

class CustomerCubit extends Cubit<Customer>{ 
CustomerCubit(Customer state) : super(state);

void login(Customer customer) => emit(customer);

void logout() => emit(null);

}

Working With The Cubit

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<CustomerCubit>(
create: (BuildContext context) => CustomerCubit(null)
),
],
child: MaterialApp(
title: 'Corey's Corner',
theme: ThemeData(
splashColor: Colors.orange,
primarySwatch: Colors.orange,
appBarTheme: AppBarTheme(elevation: 16.0),
),
home: MyHomePage(),
),
);
}
}

Using The Cubit After Our API Call

if(req.statusCode == 202){
var customer = Customer.fromReqBody(req.body);
BlocProvider.of<CustomerCubit>(context).login(customer);
// a lot more stuff
}

Using BlocBuilder Widgets

class MyHomePage extends StatelessWidget {
const MyHomePage({Key key}) : super(key: key);

@override
Widget build(BuildContext context) {
AuthAPI _authAPI = AuthAPI();
return BlocBuilder<CustomerCubit, User>(
buildWhen: (previous, current) => previous != current,
builder: (BuildContext context, Customer state){
return Scaffold(
appBar: AppBar(
title: Text("Corey\'s Corner"),
leading: state == null ?
IconButton(icon: Icon(Icons.login),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => Auth()));
},
) : null,
//more stuff

--

--

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store