how can I call function that needs context, from outside, inside widgets in flutter
881
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
Author by
Kreem Allam
Updated on December 21, 2022Comments
-
Kreem Allam over 1 year
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'); }
-
Pavel almost 4 yearsNot only from
build
. InStatefulWidget
context is available from any widget function -
Joel Broström about 2 yearsIt should be noted that the context in a stateful widget will not contain any information from the widget tree in the build method. If you create a provider in the build method and then call a method inside the provider with the global state context the provider will not be found. If you can pass the actual build context it's better to do so. If you use the refactoring tool part of a widget tree you will see that it adds BuildContext automatically.