Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to consume Provider after navigating to another route?

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!

like image 656
FlutterFirebase Avatar asked Sep 12 '19 20:09

FlutterFirebase


1 Answers

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(),
  ),
);
like image 118
haroldolivieri Avatar answered Oct 25 '22 07:10

haroldolivieri