Flutter showDialog(context) in initState method

后端 未结 4 1321
北海茫月
北海茫月 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.

提交回复
热议问题