Dmitry Bubnenkov
Dmitry Bubnenkov

Reputation: 9869

How to get access to data from Provider if class do not have context?

I am using Provider as state manager. I have few widgets that collect data. One of my widget is button that should to complete saving of all data. It have onPressed () { ... } event. I would like to do some computation of data before saving.

I thought to do it in separate class:

class ResultProcessing 
{
    // here I need access to data from provider
}

Button:

  Flexible(
    child: Container(
       child: RaisedButton(
       child: Text("Save"),
       onPressed: () {
       // I need to pass data to ResultProcessing 
       },
     )),
   ),

But the problem that I can't get access to data in Provider, because ResultProcessing class is not widget and have not context.

The class name data from which I need to grab from my processing class is Provider.of<AppState>(context).customer;

And in which moment I should to create instance of ResultProcessing? In onPressed event?

Upvotes: 0

Views: 226

Answers (3)

KiriLL Sabko
KiriLL Sabko

Reputation: 358

I solved it on a simple way. Add a required parameter to your class with a constructor and use it in the class, and then, send data from the widget where you have a build method(context) and access to the Provider.

class ResultProcessing {
    String data; // add a parameter
    ResultProcessing({required this.data}); // add the constructor
    {
        //use the data here as you want
    }
}

Upvotes: 0

JerryZhou
JerryZhou

Reputation: 5186

You can do something like this.

Flexible(
  child: Container(
   child: RaisedButton(
     child: Text("Save"),
     onPressed: () {
       DataClass data = Provider.of<DataClass>(context); 
       // Pass data to ResultProcessing
       ResultProcessing.handle(data);
     },
   ),
  ),
),

Upvotes: 1

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 277287

You don't, that's anti pattern. Your objects are purposefully not accessible outside of the widget tree.

You should change your approach. Instead, use widgets to act like a bridge between your model and your providers.

A typical example is ProxyProvider and similar variants

Upvotes: 1

Related Questions