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
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.
You have the proper context
. But you should use some Dialog
widgets to get the proper dialog.
showDialog(context: context, builder: (context) {
return new SimpleDialog(children: <Widget>[new Center(child: new Container(child: new Text('foo')))]);
});
you can find more dialog widgets here and here
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) async {
await showDialog<String>(
context: context,
builder: (BuildContext context) => new showDialog(
context: context,
builder: (BuildContext context) {
return new Container(child: new Text('foo'));
});
);
});
}
While this is most certainly not the smoothest way, but you can make a function that displays the dialog after a short duration, when everything is built already. It would look something like this:
void initState() {
super.initState();
_showDialog();
}
_showDialog() async {
await Future.delayed(Duration(milliseconds: 50));
showDialog(
context: context,
builder: (BuildContext context) {
return new Container(child: new Text('foo'));
});
}