void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => CounterBloc(),
child: Builder(builder: (context) {
return BlocBuilder<CounterBloc, CounterState>(
builder: (context, state) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () {
showDialog(
context: context,
builder: (_) => AlertDialog(
content:
BlocBuilder<CounterBloc, CounterState>(
builder: (context, state) {
return Container(
width: 1000,
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(5),
),
child: Column(
children: [
Row(
mainAxisAlignment:
MainAxisAlignment
.spaceBetween,
children: [
ElevatedButton(
onPressed: () {
BlocProvider.of<
CounterBloc>(
context)
.add(
DecrementCounterEvent(),
);
},
child: const Text('-'),
),
Text('${state.counter}'),
ElevatedButton(
onPressed: () {
BlocProvider.of<
CounterBloc>(
context)
.add(
IncrementCounterEvent(),
);
},
child: const Text('+'),
),
],
)
],
),
);
},
),
));
},
child: const Text('Push me')),
Text(
'${state.counter}',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
);
},
);
}),
);
}
}
I’m building a flutter app using the Bloc pattern. I am encountering a problem with dialog boxes like below. I get the error: "ProviderNotFoundException (Error: Could not find the correct Provider above this BlocBuilder<CounterBloc, CounterState> Widget". How then can I pass the right context to the showdialog()?
2
Answers
BlocProvider to provide a CounterBloc define in MyApp with home as…
And remove BlocProvider from MyHomePage.