Xenon Drey
Xenon Drey

Reputation: 171

Create a Widget Exactly at the center of the Row - Flutter

I want to make like and dislike button (the green Container) exactly at the center of the row

enter image description here

Here is my Code

Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
  children: <Widget>[
    Icon(Icons.comment),
    Container(
      width: 150,
      color: Colors.greenAccent,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Icon(Icons.keyboard_arrow_up),
          Stack(
            children: <Widget>[
              Container(
                width: 30,
                height: 10,
                color: Colors.black,
              ),
            ],
          ),
          Icon(Icons.keyboard_arrow_down),
        ],
      ),
    ), 

How to do this?

Upvotes: 0

Views: 124

Answers (1)

Afridi Kayal
Afridi Kayal

Reputation: 2285

You can use a stack with the first child as the row and second as the green box aligned to the center of the screen. Check this: Dartpad code

Stack(fit: StackFit.expand, children: [
  // The icon and text in this row
  Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.center, // Align the items to the center vertically
      children: [Icon(Icons.message), Text('Current Date')]),
  // Draw the green container in the next layer of the stack above the row layer
  // Align it to center
  Align(
    alignment: Alignment.center,
    child: Container(
      width: 150,
      color: Colors.greenAccent,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Icon(Icons.keyboard_arrow_up),
          Container(
            width: 30,
            height: 10,
            color: Colors.black,
          ),
          Icon(Icons.keyboard_arrow_down),
        ],
      ),
    ),
  )
]);

Note: This ensures your green box is in the exact center all the time but if the screen size is small enough, the green box will obscure the row elements behind. Try reducing the size of the screen in the dartpad example to see this behaviour.

Upvotes: 1

Related Questions