Flutter showDialog(context) in initState method

后端 未结 4 1293
北海茫月
北海茫月 2021-01-05 08:25

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

相关标签:
4条回答
  • 2021-01-05 08:57

    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.

    0 讨论(0)
  • 2021-01-05 08:57

    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

    0 讨论(0)
  • 2021-01-05 08:58
    @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'));
              });
          );
        });
      }
    
    0 讨论(0)
  • 2021-01-05 09:11

    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'));
            });
      }
    
    0 讨论(0)
提交回复
热议问题