Suppose I have an AppBar:
final AppBar myAppBar = AppBar(
leading: IconButton(
icon: Icon(Icons.delete),
onPressed: () {},
),
);
If I want to reference the main parent context in that onPressed
function, is there a way to reference the variable without creating a new class or creating a function which takes the context as an argument for constructing a new component?
final AppBar myAppBar = AppBar(
leading: IconButton(
icon: Icon(Icons.delete),
onPressed: () { print(this.context); },
),
);
You said the parent Widget
was a MaterialApp
, so in order to access the BuildContext
of a parent Widget
, you can use the BuildContext
of the child Widget
in the following way:
class Foo extends StatefulWidget {
...
}
class FooState extends State<Foo> {
...
BuildContext getParentContext() {
return context.ancestorStateOfType(const TypeMatcher<MaterialApp>()).context;
}
}
If you don't have access to the child's BuildContext
, then you have 2 other options:
BuildContext
when the child requires it: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
directly to the child as a parameter.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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With