![](/img/trans.png)
[英]Riverpod context.read() just returns the data type in the provider, so I can't update the value
[英]Flutter Riverpod context.read vs Provider in the build method
在 Riverpod文檔中,它說:
這就是
context.read(myProvider)
是一個解決方案的地方。使用它,我們可以將之前的代碼重構為:
@override Widget build(BuildContext context) { return RaisedButton( onPressed: () => context.read(counterProvider).state++, child: Text('increment'), ); }
通過這樣做,點擊我們的按鈕仍然會增加計數器。 但是我們不再聽取提供者的意見,這避免了不必要的重建。
但后來它說:
警告
避免在 Widget 的
build
方法中調用context.read
。 如果要優化重建,請提取在 Provider 中偵聽的值。
這讓我有點困惑。 首先,文檔給出了在build
方法中使用context.read
的示例,然后給出了避免它的警告。 為什么?
在布局期間可以多次調用build
方法。 因此你應該避免在其中做任何額外的工作(比如在你的模型上調用一個方法)。
但是,在調用build
時實際上不會調用RaisedButton
的onPressed
回調。 onPressed
僅在用戶按下按鈕時調用。 只有這樣,Riverpod 才會讀取您的提供者並調用模型上的方法。 所以文檔中的警告不適用於這種情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.