Home > Software engineering >  How to Center Children of Row Widgets
How to Center Children of Row Widgets

Time:12-18

I have a horizontal ListView with three Containers, I want to center the content/children of the Rows within the Containers. I have tried MainAxisAlignment.center but it does not seem to work for me.

This is the code, the mainAxisAlignment has been commented although I have tried using it to no avail.

Container(
      padding: const EdgeInsets.symmetric(horizontal: 4.0),
      width: 134.0,
      decoration: const BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(8.0)),
        color: Color(0xFFFF7700),
      ),
      child: Row(
        // mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            urlImage,
            height: 45.0,
            width: 45.0,
          ),
          const SizedBox(width: 4.0),
          Flexible(
            child: Text(
              title,
              style: const TextStyle(
                fontSize: 14.0,
                fontWeight: FontWeight.w600,
                color: Colors.white,
              ),
            ),
          ),
        ],
      ));

ListView Image

CodePudding user response:

First, both children of the column should be wrapped inside Expanded. Then, check textAlign property of Text and set it to center

  home: Scaffold(
      body: Builder(builder: (context) {
        return Container(
            padding: const EdgeInsets.symmetric(horizontal: 4.0),
            width: 134.0,
            child: Container(
              decoration:
                  BoxDecoration(border: Border.all(color: Colors.green)),
              child: Row(
                // mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Expanded(
                      child: Container(
                    decoration: BoxDecoration(
                        border: Border.all(color: Colors.red)),
                    child: const Text('smth'),
                  )),
                  const SizedBox(width: 4.0),
                  Expanded(
                    child: Container(
                      decoration: BoxDecoration(
                          border: Border.all(color: Colors.red)),
                      child: const Text(
                        'title',
                        style: TextStyle(
                          fontSize: 14.0,
                          fontWeight: FontWeight.w600,
                          color: Colors.black,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
                ],
              ),
            ));
      }),
    ));

RESULT

enter image description here

I wrapped them with border colors so you can see the difference. When both are wrapped with Expanded, they take the same space and now you can center the text.

  • Related