16

My app have 2 type of user: admin and normal. I show admin screen to admin and normal screen to normal user. All user need access Provider model1. But only admin need access model2.

How I can initialise only model2 for admin user?

For example:

class MyApp extends StatelessWidget {
  final model1 = Model1();

  final model2 = Model2();

  @override
  Widget build(BuildContext context) {

return MultiProvider(
    providers: [
ChangeNotifierProvider(builder: (_) => model1),
      ChangeNotifierProvider(builder: (_) => model2),
    ],
    child: MaterialApp(

I want to put model2 only in AdminScreen. But if I do this other admin pages cannot access model2 after Navigator.push because they are not descendant of AdminScreen.

Thanks for help!

haroldolivieri
  • 2,173
  • 18
  • 29
FlutterFirebase
  • 2,163
  • 6
  • 28
  • 60

1 Answers1

23

You can pass the existing model forward creating a new ChangeNotifierProvider using the value of the existing one.

For that, you need to use ChangeNotifierProvider.value constructor passing the existing model2 as the value.

If you already have an instance of ChangeNotifier and want to expose it, you should use ChangeNotifierProvider.value instead of the default constructor.

MaterialPageRoute(
  builder: (context) => ChangeNotifierProvider<Model2>.value(
    value: model2,
    child: SecondRoute(),
  ),
);
balu k
  • 3,515
  • 2
  • 14
  • 29
haroldolivieri
  • 2,173
  • 18
  • 29
  • 2
    Thanks for reply! You are correct with `ChangeNotifierProxyProvider` I can access `model1`. But this will only be scope to page where I access it. `model2` will not be available to other Navigation route after `Navigator.push()`. You can give example? – FlutterFirebase Sep 13 '19 at 07:02
  • 1
    wrap the pushed child into a `ChangeNotifierProxyProvider` so you can copy the existing model2's state – haroldolivieri Sep 13 '19 at 07:43
  • Thanks!! I have try but I cannot understand how to do. I still get error cannot find correct provider. Are you mean like this: `Navigator.push(model2)`. You can give code? – FlutterFirebase Sep 13 '19 at 08:10
  • @FlutterFirebase I've changed my answer as ProxyProvider will not fix your problem – haroldolivieri Sep 13 '19 at 09:52
  • 2
    Is there a way to expose th model by using named push method? – smarteist Apr 02 '20 at 19:37
  • you can pass as a param when declaring the routes, then you can create the `ChangeNotifierProvider` using this param inside the destination widget – haroldolivieri Apr 04 '20 at 21:41