0
votes

If I only want a widget and its children have specific Provider but not in whole app, how do I achieve that ?

// not this
  void main() {
     runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => CartModel()),
        Provider(create: (context) => SomeOtherClass()),
      ],
      child: MyApp(),
       ),
     );
   }
2

2 Answers

0
votes

You just need to wrap MultiProvider to the Widget you want. Like this:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MultiProvider(
        providers: [Provider(create: (context) => TestModel(index: 1)),],
        child: MyHomePage(title: 'Flutter Demo Home Page')
      ),
    );
  }
}
0
votes

You can wrap this widget with the provider and can be used as

final _myProvider=Provider.of<MyProvider>(context, listen: false);

or using

Consumer<MyProvider>(
 builder: (BuildContext context, MyProvider myProvider, Widget child) {
   return child;
),