🔥

【Flutter】Row, ColumnでSpacingを使いたい!

2023/01/18に公開

【Flutter】Row, ColumnでSpacingを使いたい!

Pattern: Wrap

Wrap(
  spacing: 20, // to apply margin in the main axis of the wrap
  runSpacing: 20, // to apply margin in the cross axis of the wrap
  children: <Widget>[
     Text('child 1'),
     Text('child 2')
  ]
)

Pattern: Column to Wrap

Wrap(
  direction: Axis.vertical,
  spacing: 20,
  runSpacing: 20,
  children: <Widget>[
     Text('child 1'),
     Text('child 2')
  ]
)

Pattern: Column with map Padding

ただし、すべてのアイテムにpaddingが付与されるのでspacingとはイコールではない

Column(
      children: [Text('child 1'), Text('child 2')]
          .map(
            (e) => Padding(
              padding: const EdgeInsets.all(8),
              child: e,
            ),
          )
          .toList(),
    );

Pattern: Extension

これはspacingの対象のみpaddingが付与されるのでイコール

// これと
return Column(
  children: [
    Text('Child 1'),
    SizedBox(height: 10),
    Text('Child 2'),
    SizedBox(height: 10),
    Text('Child 3'),
    SizedBox(height: 10),
    Text('Child 4'),
  ],
);
extension ListSpaceBetweenExtension on List<Widget> {
  List<Widget> withSpaceBetween({double? width, double? height}) => [
    for (int i = 0; i < length; i++)
      ...[
        if (i > 0)
          SizedBox(width: width, height: height),
        this[i],
      ],
  ];
}
// これがおなじ
Column(
  children: [
    Text('Child 1'),
    Text('Child 2'),
    Text('Child 3'),
    Text('Child 4'),
  ].withSpaceBetween(height: 10),
),

ref

https://stackoverflow.com/a/56097205

https://stackoverflow.com/a/58357507

Discussion