就像下面的官方代码示例一样,我使用了两个BlocBuilder
forCounterCubit
两个不同的事件increment
和decrement
.
它运行没有任何错误,但两个 BlocBuilders 都在调用每个事件。
我希望一个 Builder 应该调用增量,一个 Builder 应该调用减量。
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(),
),
],
),
);
}
}
我可以使用单个 CounterCubit 来实现这一点吗?
或者我需要创建两个不同的 Cubit 类,例如 IncrementCubit 和 DecrementCubit。