假设我有一个AppBar:
final AppBar myAppBar = AppBar(
leading: IconButton(
icon: Icon(Icons.delete),
onPressed: () {},
),
);
如果我想在该
onPressed
函数中引用主父上下文,是否可以在不创建新类或创建将上下文作为构造新组件的参数的函数的情况下引用变量?final AppBar myAppBar = AppBar(
leading: IconButton(
icon: Icon(Icons.delete),
onPressed: () { print(this.context); },
),
);
最佳答案
您说父Widget
是MaterialApp
,因此为了访问父BuildContext
的Widget
,可以通过以下方式使用子BuildContext
的Widget
:
class Foo extends StatefulWidget {
...
}
class FooState extends State<Foo> {
...
BuildContext getParentContext() {
return context.ancestorStateOfType(const TypeMatcher<MaterialApp>()).context;
}
}
如果您无权访问 child 的
BuildContext
,那么您还有另外两个选择:BuildContext
:class FooParent extends StatelessWidget {
...
@override
Widget build(BuildContext context) {
return Foo(onProvideParentContext: () => context);
}
}
typedef ContextProvider = BuildContext Function();
class Foo extends StatefulWidget {
final ContextProvider onProvideParentContext;
Foo({
@required this.onProvideParentContext,
});
...
}
class FooState extends State<Foo> {
...
BuildContext getParentContext() {
return widget.onProvideParentContext();
}
}
BuildContext
直接作为参数传递给 child 。 class FooParent extends StatelessWidget {
...
@override
Widget build(BuildContext context) {
return Foo(parentContext: context);
}
}
class Foo extends StatefulWidget {
final BuildContext parentContext;
Foo({
@required this.parentContext,
});
...
}
class FooState extends State<Foo> {
...
BuildContext getParentContext() {
return widget.parentContext;
}
}
关于dart - 在Dart/Flutter中定义变量并引用父上下文,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56194859/