BuildContext 与状态上下文

BuildContext vs State Context

我注意到一个state的build方法传入了一个BuildContext,我也注意到State本身也有一个叫context的成员。我在想什么时候用BuildContext合适,什么时候用成员变量合适?它们可以互换吗?

是否有时使用一个而不是另一个会导致错误?我们如何采取措施确保我们不会这样做?

来自 flutter documentation for State 和构建函数:

The BuildContext argument is always the same as the context property of this State object and will remain the same for the lifetime of this object. The BuildContext argument is provided redundantly here so that this method matches the signature for a WidgetBuilder.

它们完全相等。

可能不明显,但作为参数传递给 buildBuildContext 永远不会改变。

Statecontext 字段仅指向常量 BuildContext。 为什么重复?因为 StatefulWidgets 会随时间更新。 因此,您可能需要在 didUpdateWidget.

等方法中访问此 BuildContext

StatelessWidget 不需要它,因为它仅作为 build 方法。