Search code examples
flutterflutter-layout

I can't center positioned widget


I must use Stack and Positioned widgets for my layout but also I need to make sure my widgets are centered so I can't use left, right.

  Widget _body() {
    return Stack(
      children: <Widget>[
        Positioned(
          left: 0,
          child: _animation(),
        ),
        Positioned(
          top: 300,
          child: Text(
            "Centered Text",
            style: TextStyle(color: Colors.black87, fontSize: 30),
          ),
        Positioned(
          top: 350,
          child: Text(
            "Second Centered Text",
            style: TextStyle(color: Colors.black87, fontSize: 30),
          ),
        ),
      ],
    );
  }

The text widget should be centered.


Solution

  • You should use Align in your second widget.

    Widget _body() {
      return Stack(
        children: <Widget>[
          Positioned(
            left: 0,
            child: Text("Text here"),
          ),
          Align(
            child: Text(
              "Centered Text",
              style: TextStyle(color: Colors.black87, fontSize: 30),
            ),
          ),
        ],
      );
    }