我有一个列小部件与两个TextField小部件作为孩子,我想在他们之间有一些空间。

我已经尝试过mainAxisAlignment: mainAxisAlignment。但结果不是我想要的。


当前回答

受https://stackoverflow.com/a/70993832/14298786的启发,在List<Widget>上使用扩展来添加sizebox:

extension on List<Widget> {
  List<Widget> insertBetweenAll(Widget widget) {
    var result = List<Widget>.empty(growable: true);
    for (int i = 0; i < length; i++) {
      result.add(this[i]);
      if (i != length - 1) {
        result.add(widget);
      }
    }
    return result;
  }
}

像这样使用:

Column(children: [
  Widget1(),
  Widget2(),
  Widget3(),
].insertBetweenAll(SizedBox(height: 20)))

其他回答

如果你不想包装填充与每个小部件或重复大小框。

试试这个:

Column(
        children: [
          Widget(),
          Widget(),
          Widget(),
          Widget(),
        ]
            .map((e) => Padding(
                  child: e,
                  padding: const EdgeInsets.symmetric(vertical: 10),
                ))
            .toList(),
      ),

这将扭曲所有的小部件与填充没有重复。

你可以用不同的方法来解决这个问题。

如果使用行/列,则必须使用mainAxisAlignment: MainAxisAlignment.spaceEvenly 如果你使用Wrap Widget,你必须使用runSpacing: 5, spacing: 10日, 在任何地方都可以使用SizeBox()

在这种情况下,大小框将不起作用,手机处于横向模式。

body: Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        Expanded(
           child: Container(
            margin: EdgeInsets.all(15.0),
            decoration: BoxDecoration(
              color: Color(0xFF1D1E33),
              borderRadius: BorderRadius.circular(10.0),
            ),
          ),
        ),
        Expanded(
           child: Container(
            margin: EdgeInsets.all(15.0),
            decoration: BoxDecoration(
              color: Color(0xFF1D1E33),
              borderRadius: BorderRadius.circular(10.0),
            ),
          ),
        ),
        Expanded(
           child: Container(
            margin: EdgeInsets.all(15.0),
            decoration: BoxDecoration(
              color: Color(0xFF1D1E33),
              borderRadius: BorderRadius.circular(10.0),
            ),
          ),
        ),
      ],
     )

这是另一个涉及for循环的选项。

Column(
  children: <Widget>[
    for (var i = 0; i < widgets.length; i++)
      Column(
        children: [
          widgets[i], // The widget you want to create or place goes here.
          SizedBox(height: 10) // Any kind of padding or other widgets you want to put.
        ])
  ],
),

还可以使用辅助函数在每个子元素之后添加空格。

List<Widget> childrenWithSpacing({
  @required List<Widget> children,
  double spacing = 8,
}) {
  final space = Container(width: spacing, height: spacing);
  return children.expand((widget) => [widget, space]).toList();
}

因此,返回的列表可以用作列的子元素

Column(
  children: childrenWithSpacing(
    spacing: 14,
    children: [
      Text('This becomes a text with an adjacent spacing'),
      if (true == true) Text('Also, makes it easy to add conditional widgets'),
    ],
  ),
);

我不确定,如果它是错误的或有一个性能惩罚运行的孩子通过一个帮助函数为相同的目标?