如何将数据从一种提供程序模型传递到另一种? [英] How to pass data from one provider model to another?

查看:93
本文介绍了如何将数据从一种提供程序模型传递到另一种?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要使用 provider ChangeNotifierProvider )和 ChangeNotifier 用于管理应用程序状态。但是我如何从另一个模型的一个模型访问状态?

I want use provider (ChangeNotifierProvider) and ChangeNotifier for manage app state. But how I can access state from one model in another model?

用例:在聊天应用程序中,一个模型用于存储用户信息。其他模型使用用户信息(例如,用户ID)来调用数据库(Firestore)并获取聊天数据流。

Use case: In chat app, one model for store user information. Other model use user information (for example user id) to make call to database (Firestore) and get stream of chat data.

例如:

class Model1 extends ChangeNotifier {
  final List<Item> items = [];

class Model2 extends ChangeNotifier {
//Access items from Model1 here
items;

这可能吗?我不喜欢模型太大,因为很难维护。

Is this possible? I not like have very big Model because is hard to maintain.

谢谢!

推荐答案

使用 provider ,一个模型无法访问另一个模型。

Using provider, one model doesn't access another model.

您应该使用 ProxyProvider ,以合并其他模型。

Instead, you should use ProxyProvider, to combine a model from others.

您的模型如下:

class Foo with ChangeNotifier {
  int count = 0;

  void increment() {
    count++;
    notifyListeners();
  }
}

class Bar with ChangeNotifier {
  int _count;
  int get count => _count;
  set count(int value) {
    if (value != count) {
      _count = value;
      notifyListeners();
    }
  }
}

然后您可以使用 ChangeNotifierProxyProvider 这样(假设您的小部件树中有较高的`ChangeNotifierProvider):

And then you can use ChangeNotifierProxyProvider this way (assuming there's a `ChangeNotifierProvider higher in your widget tree):

ChangeNotifierProxyProvider<Foo, Bar>(
  initialBuilder: (_) => Bar(),
  builder: (_, foo, bar) => bar
    ..count = foo.count, // Don't pass `Foo` directly but `foo.count` instead
)

这篇关于如何将数据从一种提供程序模型传递到另一种?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆