Home > other >  Flutter: Showdialog not able to access the provider from context
Flutter: Showdialog not able to access the provider from context

Time:07-11

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.

CodePudding user response:

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(),
      ),
    );
  }
}
  • Related