Shiv
Shiv

Reputation: 109

Where to place a Provider Widget -- Flutter Provider Package

I am currently learning app development with Flutter and have started learning about the Provider package. I was having some difficulty and was getting the error:

"Could not find the correct Provider above this ... Widget"

I ended up moving the Provider widget to wrap around my MaterialApp widget instead of my Scaffold Widget, and that seemed to fix things.

That being said, I'm not sure why this fixed things. Are we supposed to put our Provider widget around our MaterialApp? If so, can someone please explain why this is needed? If not, can someone explain how to determine where to place the Provider widget in our tree?

Upvotes: 3

Views: 2712

Answers (4)

Subarata Talukder
Subarata Talukder

Reputation: 6281

The best practice of using provider:

Place the Provider widget at the top of the widget tree. Bellow I put a template code that can be used for one more providers at the same place, by using MultiProvider widget under Provider package.

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ProviderName<ModelName>(create: (_) => ModelName()),
        AnotherProviderName<AnotherModelName>(create: (_) => AnotherModelName()),
      ],
      child: MaterialApp(
        title: 'App title',
        theme: ThemeData(
              primarySwatch: Colors.blue,
              primaryColor: const Color(0xFF2196f3),
              accentColor: const Color(0xFF2196f3),
              canvasColor: const Color(0xFFfafafa),
        ),
        home: MyHomePage(), // Your widget starting
      ),
    );
  }
}

For more informatin: https://pub.dev/documentation/provider/latest/

Upvotes: 1

Khaled Mahmoud
Khaled Mahmoud

Reputation: 343

You could add it to any route and pass it to the route you need to use or you can add it to MaterialApp so you can use it anywhere.

Upvotes: 1

Alexey Kunakov
Alexey Kunakov

Reputation: 86

If your page is a Stateful widget - inside Widget wrap State with Provider, so you can use it inside of State. This is a much cleaner solution because you won't have to wrap your entire application.

If you need the functionality of Provider everywhere in the app - yes, wrapping the entire app is completely fine, though I'll prefer to use some kind of service for this

Upvotes: 2

Oziel Guerra
Oziel Guerra

Reputation: 106

Usually, the best place is where you moved it, in the MaterialApp. This is because since that is where the app starts, the node tree will have access to the provider everywhere.

Upvotes: 4

Related Questions