I am struggling to figure out how to center a widget in an OverlayEntry
(inside an Overlay
) relative to another Widget
on the screen.
The following is a simplified version of the code I have up until now (assume it's a StatefulWidget
):
class _MyIconState extends State<MyIcon> {
// Here I get the RenderBox for the MyIcon widget and its size and coordinates
late final renderedWidget = context.findRenderObject() as RenderBox;
late final renderedOffset = renderedWidget.localToGlobal(Offset.zero);
late final renderedSize = renderedWidget.size;
// This is the OverlayEntry with the Text() Widget I'd love to center below MyIcon
late final entry = OverlayEntry(
builder: (context) => Positioned(
top: renderedOffset.dy + renderedSize.height,
left: renderedOffset.dx + (renderedSize.width / 2),
child: Text(
widget.message ?? 'Test',
textAlign: TextAlign.center,
),
),
),
);
@override
Widget build(BuildContext context) {
return widget.action != null
? GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
if (widget.action != null) {
widget.action!();
_showTooltip();
} else {
_showTooltip();
}
},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Icon(widget.icon),
),
)
: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Icon(widget.icon),
);
}
_showTooltip() {
// The screen overlay
final overlay = Overlay.of(context)!;
overlay.insert(entry);
}
}
Essentially, an Overlay
is created and positions a tooltip Text
(as an OverlayEntry
) below the MyIcon
when the icon itself is tapped.
The problem is this line of code: renderedOffset.dx + (renderedSize.width / 2)
.
I can position the text in the tooltip to start below the middle of the MyIcon
, but then the Text
keeps being written to the right, appearing decentralized.
In order to center it, I'd need to position it like so: renderedOffset.dx + (renderedSize.width / 2) - (renderedTextWidth/2)
, but the Text
is dynamic and I see no way of knowing and accounting for its width (in the example, renderedTextWidth
).
I am aware there is already a fine Tooltip
widget in Flutter that would simplify my life. Unfortunately, some requirements (independent from the issue at hand) do not allow me to use it.
So I have to come up with something custom.
This is approximately what I end up with: I'd like the red lines to be more or less vertically aligned
Have you guys every faced such an issue or have some experience regarding something similar? Do you have any tips on how to approach/solve the problem?
Thank you for any help.