方法可以自动访问构建上下文

Method has automatic access to build context

这是按下 'save' 按钮时在我的应用程序中调用的方法。该方法使用 Provider 对象访问 ChangeNotifier 实例并更新基础模型。

  /// Handle the user pressing the Submit button within the dialog.
  void _saveChanges() {
    // HANDLING DEGREE OBJECT //

    // degree title
    Provider.of<AcademicController>(context, listen: false)
        .setDegreeTitle(titleController.text);

    // degree award
    Provider.of<AcademicController>(context, listen: false)
        .setDegreeAward(awardController.text);

    // HANDLING ACADEMIC YEAR OBJECTS //

    // removing academic years to be removed
    Provider.of<AcademicController>(context, listen: false)
        .removeListOfAcademicYears(academicYearsToBeRemoved);

    // saving the changes made within to the academic year form rows
    for (AcademicYearFormRow academicYearFormRow in academicYearFormRows) {
      academicYearFormRow.saveChanges(context);
    }
  }

我很困惑,因为在这个方法中,我引用了 context,但我没有将 BuildContext 作为参数传递给函数。

该方法未嵌套,与小部件的构建方法处于同一级别。

此方法如何访问 BuildContext 而无需将其作为参数?

这取决于该方法是在 StatelessWidget 还是 StatefulWidget 中。我发现对于 StatefulWidgetcontext 在 class 中全局可用,无需将 BuildContext 的实例传递给任何方法。

如果您的 _saveChanges 方法是 StatefulWidgetState 的成员,则 context 很可能是 State.context. The context passed to the State.build 方法State.context 并且在 State 的生命周期内不会改变。根据 State.build

的文档

The BuildContext argument is provided redundantly here so that this method matches the signature for a WidgetBuilder.