I want to center a Stack widget that includes Positioned
children. The size of the Stack is not known before rendering.
Unfortunately, the Stack seems to have an unlimited size (as seen, when wrapping a container around it).
import 'package:flutter/material.dart';
class StackTest extends StatelessWidget {
const StackTest({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.yellow,
width: 5.0,
),
),
child: buildStack()),
),
),
);
}
Widget buildStack() {
return Stack(
clipBehavior: Clip.none,
children: [
Container(),
Positioned(
top: 0,
left: 0,
child: Container(
height: 50,
width: 50,
color: Colors.red,
),
),
Positioned(
top: 50,
left: 50,
child: Container(
height: 50,
width: 50,
color: Colors.blue,
),
),
],
);
}
}
Final Question: How can I wrap a container around a stack including positioned children and center it?
Here are some similar questions, that weren't helpful for me:
Flutter - Positioned Widget in Stack causing
Stack makes infinite height if only have Positioned children
Stack
needs a reference point. So when there are only Positioned
items in it, it doesn't know where to start and how big it is.
See RenderStack
documentation: [...] If there are no non-positioned children, the stack becomes as large as possible [...]
This problem was also described here.
Solution:
Positioned
with regard to global values, like the screen size (see Priyansu Choudhury answer)