[英]Flutter, a little Cubit BlocBuilder problem
I've trying to show my int state of Cubit using BlockBuilder, that's my code:我试图使用 BlockBuilder 显示我的 Cubit 的 int state,这是我的代码:
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
void decrement() => emit(state - 1);
}
class CounterContainer extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider(create: (_) => CounterCubit(), child: CounterView());
}
}
void main() {
runApp(MaterialApp(
theme: myTheme,
home: CounterView(),
));
}
class CounterView extends StatelessWidget {
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return Scaffold(
appBar: AppBar(
title: const Text("Example"),
),
body: Center( //I guess the problem is here
child: BlocBuilder<CounterCubit, int>(builder: (context, state) {
return Text("$state", style: textTheme.headline2);
})),
//Increment and decrement button
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () => context.read<CounterCubit>().increment(),
),
const SizedBox(
height: 8,
),
FloatingActionButton(
child: const Icon(Icons.remove),
onPressed: () => context.read<CounterCubit>().decrement(),
)
],
),
);
}
}
The console error is控制台错误是
Error: Could not find the correct Provider above this BlocBuilder<CounterCubit, int> Widget
错误:在此 BlocBuilder<CounterCubit, int> 小部件上方找不到正确的提供程序
I already tried use Provider but it not resolve the problem我已经尝试过使用 Provider 但它不能解决问题
You are not using CounterContainer
, so you don't have a CounterCubit.您没有使用
CounterContainer
,因此您没有 CounterCubit。 It should be:它应该是:
void main() {
runApp(MaterialApp(
theme: myTheme,
home: CounterContainer(),
));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.