如何在颤振中获得屏幕的中心偏移量?

How can I get center offsets of a screen in flutter?

我正在使用堆栈通过偏移和定位小部件平移文本。我想获得中心的偏移量。我试过了

offset = Offset(screenWidth/2, screenHeight/2);

但这行不通,有没有其他方法可以获得中心coordinates/offset?

这是 LayoutBuilder

的示例实现
Scaffold(
  appBar: AppBar(title: Text("Center Coords")),
  body: LayoutBuilder(builder: (context, BoxConstraints constraints) =>
      Center(child:
        Column(
          children: [
            Text("center width: ${constraints.maxWidth/2}"),
            Text("center height: ${constraints.maxHeight/2}"),
          ],
        ),
      ),
    ),
  );

如果您的目标是使小部件居中,更简单的方法是使用 Align 小部件而不是 Positioned 小部件

Align(
  alignment: Alignment.center,
  child: Container(),
);

正如@pskink 评论的那样use LayoutBuilder as a parent;并且@Jared Anderton 的答案还不错,但它会计算 Scaffold 主体,而不考虑其他 属性,例如 appBar。另外@Hrvoje Čukman 回答满足你的要求。

另一件事只需使用 Stack(alignment: Alignment.center, 即可完成,它会对齐未对齐的子项。

父控件是 LayoutBuilder

  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        Offset centerOffset =
            Offset(constraints.maxWidth / 2, constraints.maxHeight / 2);
        return Scaffold(

另一种选择是从 dart:ui 获取 windowSize

 final Size windowSize = MediaQueryData.fromWindow(window).size;
  late Offset screenOffset =
        Offset(windowSize.width / 2, windowSize.height / 2);

class CenterOffset extends StatelessWidget {
  const CenterOffset({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final Size windowSize = MediaQueryData.fromWindow(window).size;
    late Offset screenOffset =
        Offset(windowSize.width / 2, windowSize.height / 2);
    return LayoutBuilder(
      builder: (context, constraints) {
        Offset centerOffset =
            Offset(constraints.maxWidth / 2, constraints.maxHeight / 2);
        return Scaffold(
            appBar: AppBar(),
            body: LayoutBuilder(
              builder: (context, chConstraints) {
                Offset bodyBasedCenter = Offset(
                    chConstraints.maxWidth / 2, chConstraints.maxHeight / 2);
                return Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text("window based center $screenOffset"),
                      Text("Parent based center $centerOffset"),
                      Text("body   based center $bodyBasedCenter"),
                    ],
                  ),
                );
              },
            ));
      },
    );
  }
}