是否有替代Navigator.push
不需要上下文?这是我的问题。
我有一个非常嵌套和深度的callstack,并不是每个函数都有一个BuildContext参数。有没有其他方法来获取当前的BuildContext,而不是通过将其从一个函数传递到另一个函数?
test1.dart
Widget build(BuildContext) {
...
new GestureDetector(
onTap: () => foo1() // very deep callstack until it calls foo30
...
}
test2.dart
void foo30() {
// need context here like:
BuildContext context = IHopeThatExists.getCurrentContext();
// why do I need that? Navigator.push needs a context or is there an alternative? FYI: I don't need to go back to the previous page though
Navigator.push(context, ..)
}
如果您的调用堆栈很深,您可能需要考虑重构= D.但除此之外,如果你使用StatefulWidget它有一个context
属性,它与传递给构建函数的属性相同。
和FYI - 来自State.build
docs:
BuildContext参数始终与此State对象的context属性相同,并且在此对象的生命周期内保持不变。这里冗余地提供BuildContext参数,以便此方法匹配WidgetBuilder的签名。
您可以使用Builder
小部件:
return Builder(
builder: (context) {
return RaisedButton(
onPressed: () {
Navigator.of(context).push(...);
},
...
);
},
);