0

How to pass the context to the show dialog in flutter. I am trying to get hold of the provider in the dialog. It's giving me following error. Works fine on the line outside of the dialog body.

Error:

The following ProviderNotFoundException was thrown building Builder(dirty): Error: Could not find the correct Provider above this Builder Widget

    Widget build(BuildContext context) {
    return ChangeNotifierProvider<IncomeProvider>(
      create: (context) => IncomeProvider(),
      child: Consumer<IncomeProvider>(
        builder: (context, provider, child) =>
          return Scaffold(
            floatingActionButton: FloatingActionButton.extended(
              onPressed: () => showDialog(
                context: context,
                builder: (context) => Center(
                  child: Material(
                    color: Colors.transparent,
                    child: Text(context.watch<IncomeProvider>().toString()),  // <--- This line gives error
                  ),
                ),
              ),
              backgroundColor: Theme.of(context).colorScheme.primary,
              label: Text(context.watch<IncomeProvider>().toString()), // <--- This is working.
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
RV.
  • 2,781
  • 3
  • 29
  • 46
  • Can you include full [minimal-reproducible-example](https://stackoverflow.com/help/minimal-reproducible-example) widget that will reproduce the same issue? – Md. Yeasin Sheikh Jul 10 '22 at 03:45
  • 1
    Take a look at this:https://stackoverflow.com/questions/57547784/how-to-access-provided-provider-of-value-inside-showmodalbottomsheet. – user18309290 Jul 10 '22 at 05:11

1 Answers1

2

When you are creating your providers, make them higher than MaterialApp in the main.dart file.

For example:

void main() {
    runApp(MyApp());
}

class MyApp extends StatelessWidget {    
  @override
  Widget build(BuildContext context) {
    return MultiProvider(    // <--- this is higher
      providers: [
          ChangeNotifierProvider(/* your providers */),
          ChangeNotifierProvider(/* your providers */),
          ChangeNotifierProvider(/* your providers */),
      ],
      child: MaterialApp(    // <--- this is MaterialApp
        title: 'Your App title',
        home: YourHomePage(),
      ),
    );
  }
}
WSBT
  • 33,033
  • 18
  • 128
  • 133