I'd like to use Positioned
to freely place widgets on a Stack
. It looks like by default Positioned
only offers to place its child using either left
, right
, top
, or bottom
. This has the behavior to align one of the boundaries to the given coordinate. What I'd like to achieve is to place the child at a certain x
/y
coordinate, but center it on it.
An example:
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Some App",
theme: ThemeData(
primarySwatch: Colors.green,
),
home: Scaffold(
body: Stack(children: [
Positioned(
left: 100,
top: 100,
child: SomeChild(text: "Some child"),
),
Positioned(
left: 100,
top: 100,
child: Container(width: 5, height: 5, color: Colors.red.shade900),
),
Positioned(
left: 100,
top: 150,
child: SomeChild(text: "Some child with longer text"),
),
Positioned(
left: 100,
top: 150,
child: Container(width: 5, height: 5, color: Colors.red.shade900),
),
]),
),
);
}
}
class SomeChild extends StatelessWidget {
final String text;
const SomeChild({Key? key, required this.text}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text(text);
}
}
Results in:
Basically I'd like the children to center on the small debug gizmos.
Note: I'm using SomeChild
as a placeholder for an arbitrary child whose size I neither know nor control explicitly.
Naive attempts at solving the problem where using a Center
to wrap the child, but that has no effect. I also tried to move the Positioned
into the children, doing some manual size determination within the children itself, so that they can shift their top
and right
coordiate by half their size. But that is not only awkward, and has to be implemented for every children manually, I also had problems making it work in the first place, because Stack
complained that its children are no longer either a Positioned
/Aligned
/Container
.
Is there an elegant way to center the child of a Positioned
generically?
I think this question is different from that one, because there the goal is to center a child w.r.t. the Stack
itself, not a certain coordinate.