Search code examples
paddingflutter

Is there a way to "join" Flutter Widgets with Padding?


I have a Row of Flutter widgets that I want to separate with Padding, but only between the widgets. Sort of like the behavior for the join() function for Lists, where the String you want to join is only appended between items, not at the end of the List. E.g. For something like this:

var square = new Container(height: 50.0, width: 50.0; color: Colors.pink,);
return new Row(
  children: <Widget>[
    square,
    square,
    square,
  ],
);

I'll get a row of 3 pink squares with no space between. I want a more programmatic/Flutter built-in way to do this:

const _rightPadding = const Padding(padding: const EdgeInsets.only(right: 16.0));
var square = new Container(height: 50.0, width: 50.0; color: Colors.pink,);
return new Row(
  children: <Widget>[
    square,
    rightPadding,
    square,
    rightPadding,
    square,
    // note there is no padding after this third square
  ],
);

I could add a right padding to the padding property inside my square Widget, but then I'll have extra padding at the end of the Row. I could add an if-statement that checks if I'm the last Widget in the List and not add padding for that one, though it's extra code, and I'm hoping for something more efficient. :)

I notice the Wrap Widget has runSpacing and spacing properties - this is exactly what I'm looking for, but for Rows and Columns.


Solution

  • I searched the docs for Row and couldn't find what you are looking for (although it could be there and I just not be able to see it). One way to do this programmatically is to just have a function that takes in a list of elements and return that list with padding in-between but not on the last element. Perhaps something like:

    List<Widget> createRowChildrenWithPadding(List<Widget> widgets, Padding pading) {
        var joined = List<Widget>();
    
        for (var i = 0;  i < widgets.length; i++) {
            if ( i != widgets.length - 1)  {
                joined.add(widgets[i]);
                joined.add(padding);
            } else {
                joined.add(widgets[i]);
            }
        }
        return joined;
    }
    

    Then you can just call this function and pass in the list for your row and assign the return value to the children named parameter for the Rows. Let me know if you have any questions, hope this helps!