'Using multiple BlocBuilder of same Bloc/Cubit, each for different events
Like this below official code sample, I used two BlocBuilder of CounterCubit for two different events increment and decrement.
It's running without any error, but both BlocBuilders are calling on each event.
I want one Builder should call on increment and one Builder should call on decrement.
class CounterView extends StatelessWidget {
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
BlocBuilder<CounterCubit, int>(
builder: (context, state) {
return Text('Increment $state', style: textTheme.headline2);
},
),
BlocBuilder<CounterCubit, int>(
builder: (context, state) {
return Text('Decrement $state', style: textTheme.headline2);
},
),
])),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
FloatingActionButton(
key: const Key('counterView_increment_floatingActionButton'),
child: const Icon(Icons.add),
onPressed: () => context.read<CounterCubit>().increment(),
),
const SizedBox(height: 8),
FloatingActionButton(
key: const Key('counterView_decrement_floatingActionButton'),
child: const Icon(Icons.remove),
onPressed: () => context.read<CounterCubit>().decrement(),
),
],
),
);
}
}
Can I achieve this using a single CounterCubit?
Or I need to create two different Cubit classes like IncrementCubit and DecrementCubit.
Solution 1:[1]
Your counter cubit should emit both an increment and a decrement state. One BlocBuilder is all you should use to keep it simple. Please reference the bloc documents here
Solution 2:[2]
In your cubit state, instead of just an integer, you can wrap it with a denote of your intended action (increment or decrement). Within you BlocBuilder, check the intended action and update the view. Something like this:
BlocBuilder<CounterCubit, CounterCubitState>(
builder: (context, state) {
if (state.intendedOperation == increment)
return Text('Increment $state', style: textTheme.headline2);
},
),
You can also create 2 cubits as you mentioned. That's fine, but then you will have to manage the counter value in a common store (such as a repository).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nick C. |
| Solution 2 | Phúc Nguyễn |
