Provider can't be consumed inside stateful widget of showBotttomSheet

Viewed 36

I am currently learning flutter and encountered a situation. I have a screen

  • FIND SCREEN where I have used MultiProvider to provide a FindProvider
  • Inside FindScreen I have a CustomWidget where I used showBottomSheet.
  • The showBottomSheet furhter gets a statful widget to show inside it.
  • And inside the stateful widget whenever I try to access Provider it shows the following error enter image description here Hope you guys get it, please do help. Thank you
1 Answers

You have to "re-create" your Provider to the CustomWidget with the .value like this :

ChangeNotifierProvider.value(
  value: FindProvider(), // write again the provider, cause you gonna set the already value created before in FindScreen
  child: CustomWidget(),
)

Buuttt, I recommend you to put your Provider globally, that is to say, that ALL your application has access to it and you don't have to give the value again and again and again... but how? Well, instead of creating it in your FindScreen, you create it in your MaterialApp.

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider( // something like this or MultiProvider
      create: (BuildContext context) => FindProvider(),
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: const HomeScreen(),
      ),
    );  
  }
Related