这是按下“保存”按钮时在我的应用程序中调用的方法。该方法使用 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
作为参数传递给函数。
该方法不是嵌套的,并且与小部件的 build 方法发生在同一级别。
此方法如何访问 BuildContext
而无需将其作为参数?
回答1
如果您的 _saveChanges
方法是 StatefulWidget
的 State
的成员,则 context
很可能是 https://api.flutter.dev/flutter/widgets/State/context.html。传递给 https://api.flutter.dev/flutter/widgets/State/build.html 方法的 context
始终是 State.context
,并且在 State
的生命周期内不会改变。根据 State.build
的文档
https://api.flutter.dev/flutter/widgets/BuildContext-class.html 参数在此处冗余提供,以便此方法与 https://api.flutter.dev/flutter/widgets/WidgetBuilder.html 的签名相匹配。
回答2
这取决于该方法是在 StatelessWidget
还是 StatefulWidget
内。我发现对于 StatefulWidget
,context
在类中全局可用,而无需将 BuildContext
的实例传递给任何方法。