Search code examples
flutterflutter-layout

Flutter overlay with position relative to parent


I have a ListView. I am trying to have an overlay when I click on a button that is on each element of the listview, but I can't find a way to make an overlay with a position relative to the item in the ListView.

The code I have (that was copied from some answer here in stackoverflow) is this

InkWell(          
      onTap: () {            
        return Overlay.of(context).insert(OverlayEntry(builder: (context) {
          return Align(
            child: Container(
              width: 56,
              height: 56,                
              child: Material(
                color: Colors.transparent,
                child: GestureDetector(
                  onTap: () => print('ON TAP OVERLAY!'),
                  child: Container(
                    decoration: BoxDecoration(
                        shape: BoxShape.circle, color: Colors.redAccent),
                  ),
                ),
              ),
            ),
          );
        }));           
      },
      child: Icon(
        Icons.arrow_back,
        color: Colors.black,
        size: 34,
      ),
    ),

Is there a way that the position is relative to the element in the list view (preferably dynamically, so if I scroll the list, the overlay will scroll together with the list item)

Thank you very much


Solution

  • You can use the render box to find the position of the parent.

    Then use Positioned to move the overlay to that position.

    final targetRenderBox = context.findRenderObject() as RenderBox;
    final position = targetRenderBox.localToGlobal(Offset.zero);
    
    return OverlayPortal(
      controller: controller,
      overlayChildBuilder: (context) {
        return Positioned(
          top: position.dy,
          left: position.dx,
          child: Text('Overlay'),
        );
      },
      child: child,
    );