簡體   English   中英

如何將數據從一個提供程序模型傳遞到另一個?

[英]How to pass data from one provider model to another?

我想使用provider ( ChangeNotifierProvider ) 和ChangeNotifier來管理應用程序狀態。 但是我如何從另一個模型中的一個模型訪問狀態?

用例:在聊天應用中,一種用於存儲用戶信息的模型。 其他模型使用用戶信息(例如用戶 ID)調用數據庫(Firestore)並獲取聊天數據流。

例如:

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

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

這可能嗎? 我不喜歡非常大的模型,因為很難維護。

謝謝!

使用provider ,一個模型不會訪問另一個模型。

相反,您應該使用ProxyProvider來組合其他人的模型。

您的模型將如下所示:

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):

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

v4 開始ChangeNotifierProxyProvider提供者可以像這樣構造:

ChangeNotifierProxyProvider<Foo, Bar>(
  create: (_) => Bar(),
  update: (_, foo, bar) => bar
    ..count = foo.count,
)

請注意, initialBuilder:已更改為create:builder:已更改為update:

我試圖簡單地實現這一點。

提供程序版本 ^4.3.3

這里我舉了一個簡單的例子

main.dart

ChangeNotifierProxyProvider<AuthProvider, ProductsProvider>(
       create: (context) => ProductsProvider(),
       update: (context, auth, previousProducts) => previousProducts
            ..update(auth.token, previousProducts.items == null ? [] : previousProducts.items),
),

authProvider.dart

class AuthProvider with ChangeNotifier {
  String _token;
  // _token is a response token.
  String get token {
    return _token;
}

productsProvider.dart

產品為一類單品

class ProductsProvider with ChangeNotifier {
  List<Product> _items = [];
  String _authToken;
  void update(authToken, items) {
    _items = items;
    _authToken = authToken;
    notifyListeners();
  }
}

產品.dart

class Product with ChangeNotifier {
  final String id;
  final String title;
  final String description;
  final double price;
  final String imageUrl;
  bool isFavorite;

  Product({
    @required this.id,
    @required this.title,
    @required this.description,
    @required this.price,
    @required this.imageUrl,
    this.isFavorite = false,
  });
}

我正在嘗試實現相同的場景,這是我的代碼:主文件:

        ChangeNotifierProvider<SharedPreferencesData>(
      create: (context) => SharedPreferencesData(),
    ),
    ChangeNotifierProxyProvider<SharedPreferencesData, DatabaseService>(
      create: (_) => DatabaseService(),
      update: (_, sharedPreferencesData, databaseService) {
        print('ChangeNotifierProxyProvider RAN');
        databaseService..setSpCompanyId = sharedPreferencesData.sPCompanyId;
        return null;
      },
    ),

共享首選項數據文件:

    class SharedPreferencesData with ChangeNotifier {
    String sPCompanyId = '';
    void setCompanyId(String cpID) {
     sPCompanyId = cpID;
     print('setCompanyId sPCompanyId:$sPCompanyId');
     notifyListeners();
    }
  }

數據庫服務文件:

class DatabaseService with ChangeNotifier {
  String sPCompanyId = 'empty';
  String get getSpCompanyId => sPCompanyId;

  set setSpCompanyId(String value) {
    print('value in setter database before if: $value');
    if (value != getSpCompanyId) {
      print('value in setter database: $value');
      sPCompanyId = value;
      notifyListeners();
    }
  }

DatabaseService 類不會更新。 我已經添加了打印件來弄清楚什么正在運行,什么沒有。 當我運行我的代碼時, Shared_Preferences / setCompanyId 方法中的打印正確運行。 而 main.dart 文件中的打印功能 print('ChangeNotifierProxyProvider RAN'); AND 在 DataBaseService 文件中 print('setter 數據庫中的值:$value'); 不運行。

我錯過了什么? 為什么 SharedPreferencesData 中的 notify sPCompanyId setter notifyListeners() 沒有通過 ChangeNotifierProxyProvider 更新 DatabaseService String sPCompanyId? 謝謝!

我做了這樣的事情。 我們正在傳遞“物品”。

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

>class Model2 extends ChangeNotifier {
//Access items from Model1 here
 Model1 items;
Model2(this.items);
// Now I can access items in the entire class. 
}

>ChangeNotifierProxyProvider<Model1, Model2>(
//create the class to pass the value, which is M2. 
  create: (_) => Model2(Provider.of<Model1>(context)),
  update: (_, model1, model2) => model2..items
)



>Model2 model2 = Provider.of<Model2>(context, listen: false);
>>Text(model2.items),

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM