how can I call function that needs context, from outside, inside widgets in flutter

0

Issue

I want to call a function, located in a different file, into a widget.
The function needs the widget context. how can I do this ?

// MyApp.dart
import 'foo';
class MyApp extends StatelessWidget {
  ...

  foo()

  @override
  Widget build(BuildContext context) {
   ...
}

--------
// foo.dart
void foo(){
  Navigator.of(context).pushNamed('/bar');
}

Solution

You pass the context to the function

void foo(BuildContext context){
  Navigator.of(context).pushNamed('/bar');
}

Inside a StatelessWidget is only possible to call a function that requires context from build().

Edit:
As @Pavel commented context is available in all widget function for StatefulWidget

Answered By – Benedikt J Schlegel

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More