Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get BuildContext when not available through parameter

Tags:

flutter

dart

Is there an alternative to Navigator.push which doesn't require a context? Here is my problem.

I have a very nested and deep callstack and not each function has a BuildContext parameter. Is there any other way to get the current BuildContext than through passing it from one function to another?

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, ..)
}
like image 821
Daniel Stephens Avatar asked Sep 05 '18 04:09

Daniel Stephens


2 Answers

You can use the Builder widget:

return Builder(
  builder: (context) {
    return RaisedButton(
      onPressed: () {
        Navigator.of(context).push(...);
      },
      ...
    );
  },
);
like image 92
boformer Avatar answered Nov 02 '22 13:11

boformer


If your call stack is that deep you might want to consider refactoring =D. But that aside, if you use a StatefulWidget it has a context property which is the same as what is passed to the build function.

And FYI - from the State.build docs:

The BuildContext argument is always the same as the context property of this State object and will remain the same for the lifetime of this object. The BuildContext argument is provided redundantly here so that this method matches the signature for a WidgetBuilder.

like image 26
rmtmckenzie Avatar answered Nov 02 '22 14:11

rmtmckenzie