不要在构建中调用 [read] 如果该值仅用于事件:
Widget build(BuildContext context) {
// counter is used only for the onPressed of RaisedButton
final counter = context.read<Counter>();
return RaisedButton(
onPressed: () => counter.increment(),
);
}
虽然此代码本身没有错误,但这是一种反模式。
重构小部件后很容易导致未来的错误
counter 用于其他事情,但忘记将 [read] 更改为 [watch]。
考虑在事件处理程序中调用 [read]:
Widget build(BuildContext context) {
return RaisedButton(
onPressed: () {
// as performant as the previous previous solution, but resilient to refactoring
context.read<Counter>().increment(),
},
);
}
这与之前的反模式有相同的效率,但没有
易碎的缺点。
不要使用 [read] 来创建具有永远不会改变的值的小部件
Widget build(BuildContext context) {
// using read because we only use a value that never changes.
final model = context.read<Model>();
return Text('${model.valueThatNeverChanges}');
}
虽然在其他情况发生变化时不重建小部件的想法是
好,这不应该用 [read] 来完成。
依赖 [read] 进行优化是非常脆弱和依赖的
关于实现细节。
考虑使用 [select] 过滤不需要的重建
Widget build(BuildContext context) {
// Using select to listen only to the value that used
final valueThatNeverChanges = context.select((Model model) => model.valueThatNeverChanges);
return Text('$valueThatNeverChanges');
}
虽然比 [read] 更冗长,但使用 [select] 更安全。
它不依赖于Model 上的实现细节,它使
不可能有我们的 UI 不刷新的错误。