简体   繁体   English

如果 class 没有上下文,如何从 Provider 获取数据?

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

I am using Provider as state manager.我正在使用Provider作为 state 经理。 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.它有onPressed () {... }事件。 I would like to do some computation of data before saving.我想在保存之前对数据进行一些计算。

I thought to do it in separate class:我想在单独的 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 .但问题是我无法访问Provider中的数据,因为ResultProcessing class 不是小部件并且没有context

The class name data from which I need to grab from my processing class is Provider.of<AppState>(context).customer;我需要从我的处理 class 中获取的 class 名称数据是Provider.of<AppState>(context).customer;

And in which moment I should to create instance of ResultProcessing ?在什么时候我应该创建ResultProcessing的实例? In onPressed event?onPressed事件中?

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 一个典型的例子是ProxyProvider和类似的变体

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);
     },
   ),
  ),
),

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 添加一个必需的参数,并在 class 中使用它,然后从您具有构建方法(上下文)并访问 Provider 的小部件发送数据。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM