I'm new to Flutter so this is probably easily answered by someone with more experience than me. It's more of a question about design than a code problem.

Sometimes I want to write re-usable widgets and to make them somewhat generic I want to have callbacks for user input, so that the parent widget can subscribe and then take proper actions rather than hard coding routes etc. But I directly run into trouble if I for instance wants to navigate from my callback, as I then have no context. So how do I design this in Flutter?

2 Answers

1
ishaan On

You can always have an optional/required context parameter in your stateless widgets. For stateful widgets, context is usually available, but if you need the parent context for some reason, you can always pass it to your widget. Take a look at the example below

class GenericWidgetFoo extends StatelessWidget {
  final BuildContext context;
  final Key key;
  final String name;

  const GenericWidgetFoo(
      {this.key, @required this.context, @required this.name});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Center(
          child: Text(
        this.name,
        style: TextStyle(
          color: Theme.of(context).primaryColorLight,
        ),
      )),
    );
  }
}
0
UglyBob On

As psink said above I just missed the fact that the extended State class actually has access to the context:

Properties

context → BuildContext The location in the tree where this widget builds. [...] read-only