'Method has automatic access to build context
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?
Solution 1:[1]
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.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | just95 |
| Solution 2 | Roslan Amir |
