0

I use Provider for state management and for separate business logic from UI.

I have put some Provider above MaterialApp so can access everywhere in app (for example user info).

But You don’t want to place ChangeNotifierProvider higher than necessary (because you don’t want to pollute the scope).

So I try put some Provider which are only use on some pages lower in widget tree.

For example in my purchase item flow I can have: SelectItemPage => ConfirmItemPage => CheckOutPage.

But my issue is Navigator.push() create separate widget tree every time. So if I initialise a Provider in SelectItemPage this cannot be accessed in ConfirmItemPage or CheckOutPage.

I want Provider be scope to this flow, but I cannot see how.

How I can solve this?
 Or my approach is wrong?

Edit: I know I can use prop drilling for pass data from SelectItemPage => ConfirmItemPage => CheckOutPage but this hard to maintain. I want use Provider instead of prop drilling.

FlutterFirebase
  • 2,163
  • 6
  • 28
  • 60
  • Does it help: https://dev.to/shakib609/create-a-todos-app-with-flutter-and-provider-jdh? Where each tab is getting a list based on user action. Also state managemnet and Navigation shouldn't affect each other. – skjagini Sep 11 '19 at 21:50
  • @skjagini Thanks for reply! But you article is not help. It just intialize Provider at top of widget tree. I want initialise lower and access lower in even after navigation. – FlutterFirebase Sep 13 '19 at 07:07
  • If you need across the pages, you need it root level. If you don't like the way code is organized, you can check out Redux implementation, but again there is no other option. – skjagini Sep 13 '19 at 15:29

1 Answers1

0

I think it's no other way, you mush initialize the provider on each class

try use like this on you app

on you main app

MultiProvider(
      providers: ChangeNotifierProvider<yourstate>(
          builder: (context) => yourstate,
        ),
child: MaterialApp...

on each page, you can initialize using below code

final state = Provider.of<yourstate>(context);

and use like this if you don't want to listen any change of the state

final state = Provider.of<yourstate>(context, listen: false);