Transform/Translate Flutter widget to negative 50% of it's width

Viewed 4095

Assume we have an empty parent widget (a Container), with no size, and positioned absolutely (within it's own parent) at a top/left (x/y) coordinate. Then we place a child widget (with variable size, which is not known beforehand) within the parent. Is there a way to position the child at -50% of its own width, such that the child's horizontal center appears at the x coordinate of its parent? I don't want to use global keys as there will be hundreds of instances. I've tried Transform.translate (only accepts a known x offset), FractionalOffsets, FractionallySizedBoxes, Alignments etc, but nothing seems to do what I'm trying to achieve. Does anyone know of a solution?

Edit: image demonstrating the objective enter image description here

2 Answers

As per @pskink's comment, I was able to achieve this by combining a Positioned and a FractionalTranslation

Positioned(
    left: childWidget.x,
    top: childWidget.y,
    child: FractionalTranslation(
        translation: Offset(-0.5, -0.5),
        child: childWidget,
    )
);

You can use AlignPositioned widget from align_positioned package.

AlignPositioned(
  alignment: Alignment.topLeft,
  moveByChildWidth: -0.5,          //negative 50% of child width
  child: Icon(
    Icons.info,
    size: 200,
  ),
),

Edit:

  Widget build(BuildContext context) {
    return Stack(
      children: [
        Transform.translate(
          offset: Offset(100, 200),
          child: Container(
            child: AlignPositioned(
              alignment: Alignment.topLeft,
              moveByChildWidth: -0.5,
              child: Icon(
                Icons.info,
                size: 100,
              ),
            ),
          ),
        ),
      ],
    );
  }

Gives the same result without the Container too i.e. making Transform.translate itself as the parent.

Result:

enter image description here

Related