Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a variable in Dart/Flutter and referencing parent context

Tags:

flutter

dart

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); },
  ),
);

1 Answers

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:

  1. Passing a callback which gives the parent's 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();
  }
}
  1. Passing the 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;
  }
}
like image 51
Hugo Passos Avatar answered Oct 23 '25 05:10

Hugo Passos