Flutter, a little Cubit BlocBuilder problem

Issue

I’ve trying to show my int state of Cubit using BlockBuilder, that’s my code:

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

I already tried use Provider but it not resolve the problem

Solution

You are not using CounterContainer, so you don’t have a CounterCubit.
It should be:

void main() {
  runApp(MaterialApp(
    theme: myTheme,
    home: CounterContainer(),
  ));
}

Answered By – Luis A. Chaglla

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.