Here is a method that is called within my application when a 'save' button is pressed. The method accesses a ChangeNotifier instance using the Provider object and updates the underlying model.
/// 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);
}
}
I am confused because, in this method, I reference context, but I do not pass in a BuildContext as an argument to the function.
The method is not nested and occurs at the same level as the widget's build method.
How does this method have access to a BuildContext without getting one as an argument?
CodePudding user response:
If your _saveChanges method is a member of a StatefulWidget's State, the context is most likely the State.context. The context passed to the State.build method is always the State.context and does not change over the lifetime of a State. According to the documentation of State.build
The BuildContext argument is provided redundantly here so that this method matches the signature for a WidgetBuilder.
CodePudding user response:
It depends whether that method is inside a StatelessWidget or a StatefulWidget. I find that for a StatefulWidget, the context is available globally within the class without needing to pass an instance of BuildContext to any method.
