简体   繁体   中英

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.

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM