Search code examples
flutterflutter-dependencies

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


I am using a stack to pan a text using the Offset and Positioned widgets. I want to get the offset of the center. I tried

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

But this is not working. Is there another way possible to get the center coordinates/offset?


Solution

  • As pskink commented, use LayoutBuilder as a parent; and Jared Anderton's answer is quite OK, but it will calculate the Scaffold body, without considering other properties, like appBar. Also Hrvoje Čukman's answer meets your requirement.

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

    The parent widget is 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