Ad

How Can I Get Center Offsets Of A Screen In Flutter?

- 1 answer

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?

Ad

Answer

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 LayoutBuilder.

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

Another option is getting windowSize from dart:ui.

 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"),
                    ],
                  ),
                );
              },
            ));
      },
    );
  }
}

enter image description here

Ad
source: stackoverflow.com
Ad