I'm working on something that would be similar to a Story feature like you see on Instagram or Snapchat.
My goal is to be able to add my own custom widgets, save what I create, and then display it with the widgets back in the same positions & keep it responsive.
Currently, I am using this extension:
extension GlobalKeyExtension on GlobalKey {
Rect? get globalPaintBounds {
final renderObject = currentContext?.findRenderObject();
final translation = renderObject?.getTransformTo(null).getTranslation();
if (translation != null && renderObject?.paintBounds != null) {
final offset = Offset(translation.x, translation.y);
return renderObject!.paintBounds.shift(offset);
} else {
return null;
}
}
}
Then on the Container or SizedBox of the Custom Widget I am adding, I would set a key like so:
final myCustomContainerKey = GlobalKey();
Container(
key: myCustomContainerKey,
child: ...
Saving the positionings:
'left': myCustomContainerKey.globalPaintBounds!.left,
'top': myCustomContainerKey.globalPaintBounds!.top,
'right': myCustomContainerKey.globalPaintBounds!.right,
'bottom': myCustomContainerKey.globalPaintBounds!.bottom,
When I display the UI again:
Positioned.fromRect(
rect: Rect.fromLTRB(
(left is int) ? left.toDouble() : left,
(top is int) ? top.toDouble() : top,
(right is int) ? right.toDouble() : right,
(bottom is int) ? bottom.toDouble() : bottom,
),
child: ...
This has been working pretty decent if I stay within the same device or simulator, but if I am doing this on an iPhone 14 Pro & then switch to an SE, the widgets will be in the wrong position or off-screen.
What would be the best way to save the positioning & keep it responsive among screen sizes?