0

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

2
  • 1
    That example is working for me. Could you include the version of flutter and packages that you are using, please :D May 5, 2021 at 19:08
  • Hi, @LuisA.Chaglla i'm using Flutter 2.0.5, Dart 2.12.3 and flutter_bloc: ^7.0.0. I updated my post with my main code May 5, 2021 at 20:01

1 Answer 1

0

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

void main() {
  runApp(MaterialApp(
    theme: myTheme,
    home: CounterContainer(),
  ));
}
1
  • Oh 😂😂 Really!! it worked here too, thank you so much!! May 5, 2021 at 21:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.