Home > Enterprise >  Center items in column
Center items in column

Time:11-12

I want to create two items (Circle above text, centered horizontally) according to following image:

enter image description here

I have created following code:

Column(
  crossAxisAlignment: CrossAxisAlignment.center,
  children: [
    IconButton(
      icon: const Icon(
        Icons.circle,
        color: Colors.white,
        size: 40,
      ),
      onPressed: () {},
    ),
    const Text(
      'text',
      style: TextStyle(
        color: Colors.white,
        fontSize: 16,
      ),
    ),
  ],
)

However, the result is following:

enter image description here

I found out that the problem is with the size of IconButton. When I remove this line, the icon will be smaller (as expected) and the text below would be centered. It seems that when Icon size is increased, it is not increased from the central point of the icon (to the all directions evenly), but it is increased to the right. Can somebody help me with this? Is it possible to change size of the icon without interrupting Text centering? Or is there a way to center it as needed? Thank you.

CodePudding user response:

Actually, the column Axid is centered, but the IconButton causes the issue.

Try this:

Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            IconButton(
              padding: EdgeInsets.zero, // add this
              icon: const Icon(
                Icons.circle,
                color: Colors.white,
                size: 40,
              ),
              onPressed: () {},
            ),
            const Text(
              'text',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16,
              ),
            ),
          ],
        ),

the IconButton comes by default with initial padding, removing it will show them centered horizontally.

CodePudding user response:

I have found that it is not always sufficient to add padding: EdgeInsets.zero. What you can do instead it to wrap the IconButton in a SizedBox of specified size.

The problem is that the IconButton is not aligned correctly. More info can be found here

Column(
    crossAxisAlignment: CrossAxisAlignment.center,
    children: [
        SizedBox(
            height: 50,
            width: 50,
            child: IconButton(
              padding: EdgeInsets.zero,
              alignment: Alignment.center,
              icon: const Icon(
                Icons.circle,
                color: Colors.blue,
                size: 50,
              ),
              onPressed: () {},
            ),
          ),
          const Text(
            'text',
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Colors.blue,
              fontSize: 16,
            ),
         ),
    ],
)
  • Related