'Can not remove `overlayEntry` from it's builder Widget

I have created an overlayEntry and inserted it in overlayState and in the builder method I return a GestureDetector that should remove the overlayEntry but how to implement something like overlayEntry.remove(); ?


showOverLay(BuildContext context, Widget child,
    [double top, double bottom, double right, double left]) {
  OverlayState overlayState = Overlay.of(context);
  OverlayEntry overlayEntry = OverlayEntry(
    builder: (context) {
      return Material(
        color: Colors.transparent,
        child: GestureDetector(
          onTap: () {
            /// implementation to remove `overlayEntry` there 
          },
          child: Positioned(
            top: top,
            bottom: bottom,
            right: right,
            left: left,
            child: GestureDetector(
              onTap: () {},
              child: child,
            ),
          ),
        ),
      );
    },
  );

  overlayState.insert(overlayEntry);
}


Solution 1:[1]

You can do it like this

OverlayEntry? overlay;
overlay = OverlayEntry(builder: (context) {
  return Container(
    width: 200,
    height: 200,
    alignment: Alignment.center,
    color: Colors.red,
    child: ElevatedButton(
      child: Text('click'),
      onPressed: () {
        overlay?.remove();
      },
    ),
  );
});

Overlay.of(context)?.insert(overlay);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 wenqiang zhang