在Flutter中添加OverlayEntry [英] Adding OverlayEntry in Flutter

查看:615
本文介绍了在Flutter中添加OverlayEntry的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将容器插入到叠加层中,但是此代码出现错误.

I am trying to insert a Container to the Overlay, but I had an error with this code.

class _MyHomePageState extends State<MyHomePage> {
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final entry = OverlayEntry(builder: (BuildContext overlayContext) {
      return Container(
        height: 50.0,
        width: 50.0,
        color: Colors.blue,
      );
    });
    _addOverlay(entry);
  }

  void _addOverlay(OverlayEntry entry) async {
    Overlay.of(context).insert(entry);
  }

  @override
  Widget build(BuildContext context) {
   return Scaffold(
      appBar: AppBar(
        title: Text('Flutter'),
      ),
      body: Center(),
    );
  }
}

这是错误

在构建过程中调用

setState()或markNeedsBuild().由于框架已经在构建窗口小部件中,因此无法将该叠加窗口小部件标记为需要构建.仅当其某个祖先当前正在构建窗口小部件时,才可以将其标记为需要在构建阶段中构建.允许使用此异常是因为该框架先于子级构建父级窗口小部件,这意味着将始终构建一个肮脏的后代.否则,框架可能在此构建阶段无法访问此小部件...

setState() or markNeedsBuild() called during build. This Overlay widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase...

谢谢.

推荐答案

自从上次更新为0.8.1以来,我也注意到了这一变化.我修复了此问题,以在最小延迟后添加叠加层

Since the last update to flutter 0.8.1 I noticed this change too. I fixed this to add the overlay after a minimal delay

Timer.run(() { Overlay.of(context).insert(calendarOverlay);});

现在这可行,但是感觉就像是被黑客入侵了...

Now this works but it feels like a hack...

因此,在我的构建中,当叠加层应自行显示时,我将使用此代码.

So in my build i use this code when the overlay should present itself..

如果有人有更好的解决方案,我很感兴趣;-)

If anyone has a better solution, I am interested ;-)

约翰

更新:我发现此代码也可以正常工作:

UPDATE: I found this code to be working too:

final overlay = Overlay.of(context);
WidgetsBinding.instance.addPostFrameCallback((_) => overlay.insert(entry));

它使我免于加入计时器...

It saves me from including timers...

这篇关于在Flutter中添加OverlayEntry的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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