Reputation: 540
I'm trying to use cubit for flutter counter app. I wanted to know when to provide a Bloc/Cubit to the bloc parameter in the BlocBuilder(). I tried to provide one for the below code but it did not work and got the error :
Error: Could not find the correct Provider<CounterCubit> above this CounterPage Widget
.
class CounterPage extends StatelessWidget {
const CounterPage({Key? key, required this.title}) : super(key: key);
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
centerTitle: true,
),
body: BlocBuilder<CounterCubit, int>(
bloc: CounterCubit(),
builder: (_, count) => Center(
child: Text('$count'),
)),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: FloatingActionButton(
onPressed: () => context.read<CounterCubit>().increment(),
tooltip: 'Increment',
child: Icon(Icons.add),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: FloatingActionButton(
onPressed: () => context.read<CounterCubit>().decrement(),
tooltip: 'Decrement',
child: Icon(Icons.remove),
),
),
],
),
);
}
}
This is code for cubit.
import 'package:flutter_bloc/flutter_bloc.dart';
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
void decrement() => emit(state - 1);
}
Upvotes: 2
Views: 5999
Reputation: 5343
From the official documentation:
Only specify the bloc if you wish to provide a bloc that will be scoped to a single widget and isn't accessible via a parent BlocProvider and the current BuildContext.
BlocBuilder<BlocA, BlocAState>(
bloc: blocA, // provide the local bloc instance
builder: (context, state) {
// return widget here based on BlocA's state
}
)
In your case, I would recommend providing your BLoC to the widget tree somewhere above CounterPage
like this:
BlocProvider<CounterCubit>(
create: (BuildContext context) => CounterCubit(),
child: CounterPage(),
);
Then, inside the BlocBuilder
, you won't need to specify the bloc
property:
...
body: BlocBuilder<CounterCubit, int>(
builder: (_, count) => Center(
child: Text('$count'),
)),
...
Upvotes: 1