I'm trying to use the showDialog(context, builder)
to display a greeting message when the user navigates to a certain page.
I tried this by calling the showDialog
in the initState
method of a stateful widget on that page. While it does work, it appears I don't have access to the actual context.
Is there a way in Flutter to access the context
in the initState()
method?
If not, is there another way to achieve this behaviour in a better way?
@override
void initState() {
super.initState();
new Future.delayed(Duration.zero, () {
showDialog(context: context,
builder: (BuildContext context) {
return new Container(child: new Text('foo'));
});
});
}
The member variable context can be accessed during initState but can't be used for everything. This is from the flutter for initState documentation: You cannot use [BuildContext.
Overriding of initState() method performs initialization which depends on the location at which this object was inserted into the tree (like context) or on the widget used to configure this object (or widget). In simple terms, while a page in flutter gets created on screen, this method gets called at very first.
super. initState() forwards to the default implementation of the State<T> base class of your widget. If you don't override, the default implementation will not be executed but the widget depends on that to work properly.
For newcomers, you have access to context in initState as others said. The only problem here in initState build function is not executed yet. So this context is kind of empty.
To solve this, you can use SchedulerBinding:
SchedulerBinding.instance.addPostFrameCallback((_) => doSomethingNextFrame(context));
addPostFrameCallback: Schedule a callback for the end of this frame.
Future.delayed(Duration.zero)
will also work. But I think SchedulerBinding looks cleaner.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With