我正在尝试使用showDialog(context, builder)
当用户导航到某个页面时显示问候消息。
我通过调用尝试了这个showDialog
in the initState
该页面上有状态小部件的方法。虽然它确实有效,但我似乎无法访问实际的上下文。
Flutter 有没有办法访问context
in the initState()
method?
如果没有,是否有其他方法可以更好地实现此行为?
@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 构建函数尚未执行。所以这个上下文有点空。
要解决这个问题,您可以使用调度程序绑定 https://api.flutter.dev/flutter/scheduler/SchedulerBinding/addPostFrameCallback.html:
SchedulerBinding.instance.addPostFrameCallback((_) => doSomethingNextFrame(context));
addPostFrameCallback:安排此帧结束时的回调。
Future.delayed(Duration.zero)
也会起作用。但我认为 SchedulerBinding 看起来更干净。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)