Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter showDialog(context) in initState method

Tags:

flutter

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'));
    });
  });
}
like image 528
TommyF Avatar asked Aug 09 '18 12:08

TommyF


People also ask

Can I use context in initState flutter?

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.

How do I override initState flutter?

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.

What is super initState () in flutter?

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.


1 Answers

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.

like image 83
Sait Banazili Avatar answered Sep 27 '22 23:09

Sait Banazili