Kreem Allam
Kreem Allam

Reputation: 183

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

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

Upvotes: 2

Views: 2025

Answers (1)

Benedikt J Schlegel
Benedikt J Schlegel

Reputation: 1939

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

Upvotes: 1

Related Questions