我已经知道,构建上下文可以在StatefulWidget中的任何地方使用,但仅在使用Stateless Widget时可以在构建函数中使用。小部件中有太多内容需要引用构建上下文,例如Theme
,showDialog
,Navigator
,Provider
...
例如,我在StatelessWidget中有以下代码:
@override
Widget build(BuildContext context){
...
_getFirstWidget();
...
}
...
Widget _getFirstWidget(){
return _getSecondWidget();
}
Widget _getSecondWidget(){
return _getThirdWidget();
}
Widget _getThirdWidget(){
// use build context here
}
...
如果我想在小部件的末尾使用构建上下文,我想到了三种方法:
为什么Flutter在StatelessWidget中设置了此限制?
答案 0 :(得分:0)
我不太确定,但是我想您想使用函数'_getThirdWidget()'中的build方法的BuildContext。您可以将其作为如下参数传递:
Widget _getThirdWidget(BuildContext context) {
// Use the context here
}
// Call the function like this in the parent widget
@override
Widget build(BuildContext context) {
return _getThirdWidget(context);
}
让我知道这是否回答了您的问题!