How to pass data from one provider model to another?

旧城冷巷雨未停 提交于 2019-12-10 18:49:33

问题


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

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.

For example:

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.



Thanks!


回答1:


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

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

Your models would look like:

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

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
)


来源:https://stackoverflow.com/questions/56798046/how-to-pass-data-from-one-provider-model-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!