ebg11
ebg11

Reputation: 1046

Flutter state management issue

My problem is related to the provider pattern/library.

I have created some state classes as follows (ive replaced content/var names to try and keep it simple)

class State1 with ChangeNotifier{

String _s;

  set s(String newS){
    _s = newS;
    notifyListeners();
  }

}

and then I use a multiprovider to pass it (create the objects in the widget init which acts as parent to everything in the app.)

child: MultiProvider(
        providers: [
          ChangeNotifierProvider(builder: (context) => state1),
        ],
        child: Stack(
        alignment: Alignment.center,
        children: stackChildren,
      ),

Which is then accessed in the children widgets build method using

 state1Var = Provider.of<State1>(context);

And all of this works fine..

My issue is when I get to using a navigation push I can no longer access the state.

onPressed: (() {
          Navigator.push(
            contextField,
            MaterialPageRoute(builder: (context) => NewPage()),
          );
        }),

As i get this error

Could not find the correct Provider<State1> above this NewPage Widget...

I did manage to get it using this

  Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => Consumer(builder: (),child: NewPage(),)),
          );

But when I popped the widget using navigator.pop() the state couldnt be used as it said it had been disposed. Am i doing this incorrectly or is there something i am missng?

Sorry if i've made this complicated. I had to remove a lot of code.

Thanks for your help :)

Upvotes: 0

Views: 948

Answers (1)

Mehmet Esen
Mehmet Esen

Reputation: 6876

Probably you have a context hierarchy problem. Wrap your MaterialApp with MultiProvider or your Provider must be on top of the Route you are getting the provider within.

Otherwise, you can wrap your Scaffold with Consumer widget. What Consumer does is, simply it's a builder for establishing a connection between your Provider and Route by creating yet another context and lets you to obtain Provider class via InheritedWidget.

Upvotes: 3

Related Questions