initState方法中的flutter showDialog(context) [英] Flutter showDialog(context) in initState method

查看:156
本文介绍了initState方法中的flutter showDialog(context)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用showDialog(context, builder)在用户导航到特定页面时显示问候消息.

I'm trying to use the showDialog(context, builder) to display a greeting message when the user navigates to a certain page.

我通过在该页面上的有状态小部件的initState方法中调用showDialog来尝试此操作.尽管它确实起作用,但看来我无权访问实际上下文.

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.

Flutter中是否可以通过initState()方法访问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'));
    });
  });
}

推荐答案

对于新手,您可以像其他人所说的那样在initState中访问上下文. initState构建函数中的唯一问题尚未执行.因此,此上下文是空的.

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.

要解决此问题,您可以使用 SchedulerBinding :

To solve this, you can use SchedulerBinding:

SchedulerBinding.instance.addPostFrameCallback((_) => doSomethingNextFrame(context));

addPostFrameCallback:为该帧的结尾安排一个回调.

addPostFrameCallback: Schedule a callback for the end of this frame.

Future.delayed(Duration.zero)也将起作用.但是我认为SchedulerBinding看起来更干净.

Future.delayed(Duration.zero) will also work. But I think SchedulerBinding looks cleaner.

这篇关于initState方法中的flutter showDialog(context)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆