Home > Software engineering >  How can I get center offsets of a screen in flutter?
How can I get center offsets of a screen in flutter?

Time:01-29

I am using a stack to pan a text using offset and positioned widget. I want to get the offset of the center. I tried

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

But this is not working, is there any other way possible to get the center coordinates/offset?

CodePudding user response:

Here is a sample implementation of the 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}"),
          ],
        ),
      ),
    ),
  );

CodePudding user response:

If your goal is to center your widget, the easier way is to use the Align widget instead of the Positioned widget

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

CodePudding user response:

As @pskink commented use LayoutBuilder as a parent ; and @Jared Anderton answers is quite ok, but it will calculate the Scaffold body, without considering other property like appBar. Also @Hrvoje Čukman answer meet your requirement.

Another thing can be done just using Stack(alignment: Alignment.center, it will align unaligned children.

The parent widget be enter image description here

  •  Tags:  
  • Related