Continuing from our basic introduction to Cubits where we used a cubit to manage state, we will now use a cubit in a UI.
In case you haven't read the starting post please go and read this up.
Let us discuss the new items here. We will start with main
void main() {
BlocOverrides.runZoned(() {
runApp(const VsjApp());
});
}
What is BlocOverrides.runZoned(()?
The official documentation says that
it is a static method of the blocOverrides class that
Runs body in a fresh Zone using the provided overrides
Runs body in a fresh Zone using the provided overrides
What is a body?
The official documentation gives this.
R runZoned<R>(
R body(),
{BlocObserver? blocObserver,
EventTransformer? eventTransformer}
)
Body is code block that contains a BlocObserver and an EventTransformer.
Steps in using a Cubit.
1. class VsjApp extends StatelessWidget {
const VsjApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => VsjCubit(),
child: const VsjCubitView(),
);
}
}
You create a cubit and an app showing the cubit state.
class VsjCubitView extends StatelessWidget {
const VsjCubitView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocBuilder<VsjCubit, bool>(
builder: (context, b) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Vsj Cubit Demo'),
backgroundColor: Colors.teal,
centerTitle: true,
),
body: Center(
child: Text(
'Boolean Value: $b',
style: const TextStyle(fontSize: 32),
),
),
floatingActionButton: Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
ElevatedButton(
child: const Text("Toggle"),
onPressed: () {
context.read<VsjCubit>().toggleBoolean();
},
),
],
),
),
);
},
);
}
}
Return the UI in this manner.
return BlocBuilder<VsjCubit, bool>(
builder: (context, b) {
Here is the cubit.
class VsjCubit extends Cubit<bool> {
VsjCubit() : super(true);
@override
void onChange(Change<bool> change) {
super.onChange(change);
print(change);
}
@override
void onError(Object error, StackTrace stackTrace) {
print('$error, $stackTrace');
super.onError(error, stackTrace);
}
void toggleBoolean() {
emit(state ? false : true);
}
}
We build a Cubit and use it in a UI/
0 Comments