Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I dynamically align Widgets in a Row in Flutter?

I have a widget that consists of a Row() with MainAxisAlignment.spaceEvenly, and has three IconButton as children.

The third button uses a bool showButton in a ternary operator to toggle whether the third button is displayed or not.

My issue is when the button is not being displayed, the Row spacing still accounts for the empty Container (as seen in the pics at the bottom).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Besides creating two separate Rows with two and three buttons (to toggle between) is there a better method for spacing these buttons, or is there an alternative to an empty Container that won’t take up space in my alignment?

Row(
  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  children: [
    IconButton(
      onPressed: () {...},
      icon: Icon(...),
    ),
      IconButton(
      onPressed: () {...},
      icon: Icon(...),
    ),
    showButton
        ? Container()
        :  IconButton(
      onPressed: () {...},
      icon: Icon(...),
    ), 
  ],
),

3 buttons

2 buttons

>Solution :

Instead of using ternary operator to show an empty Container when the condition is false, you can conditionally include the item in the list by doing this:

children: [
  // ...
  if (showButton) IconButton(...),
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading