我有一个列小部件与两个TextField小部件作为孩子,我想在他们之间有一些空间。
我已经尝试过mainAxisAlignment: mainAxisAlignment。但结果不是我想要的。
我有一个列小部件与两个TextField小部件作为孩子,我想在他们之间有一些空间。
我已经尝试过mainAxisAlignment: mainAxisAlignment。但结果不是我想要的。
当前回答
这是另一个涉及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.
])
],
),
其他回答
您可以使用Wrap()小部件代替Column()在子小部件之间添加空格。并使用spacing属性给予子元素之间相等的间距
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')
]
)
最好使用Wrap小部件,而不是列或行。
包装( 间距:10, runSpacing: 10, 孩子们:[], )
您可以使用Padding来包装每个子部件,然后设置Padding的顶部或底部。
如果你不想写很多相同的数字,你可以这样写:
Column(
children: [
child1,
child2,
...,
childN
].map((e) => Padding(padding: EdgeInsets.only(top: 10), child: e)).toList()
);
我也希望在Flutter中有一些内置的方法来做到这一点。就像一个参数,你可以传递给列或行。有时你不希望每个元素都有填充,但希望元素之间有空格。特别是如果你有两个以上的孩子,写这样的东西有点乏味
const double gap = 10;
return Column(
children: [
Text('Child 1'),
SizedBox(height: gap),
Text('Child 2'),
SizedBox(height: gap),
Text('Child 3'),
SizedBox(height: gap),
Text('Child 4'),
],
);
然而,我想出了一个快速(不完美)的解决方案:
在你的项目中添加这个(只有一次):
extension ListSpaceBetweenExtension on List<Widget> {
List<Widget> withSpaceBetween({double? width, double? height}) => [
for (int i = 0; i < this.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),
),
当使用Row时,你必须用width替换height。
你可以试试这个:
import 'package:flutter/material.dart';
class CustomColumn extends Column {
CustomColumn({
Key? key,
MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start,
MainAxisSize mainAxisSize = MainAxisSize.max,
CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.center,
TextDirection? textDirection,
VerticalDirection verticalDirection = VerticalDirection.down,
TextBaseline? textBaseline,
List children = const [],
EdgeInsetsGeometry? rowPadding,
}) : super(
children: children.map((e) => Padding(padding : rowPadding ?? EdgeInsets.only(bottom:12), child : e)).toList(),
key: key,
mainAxisAlignment: mainAxisAlignment,
mainAxisSize: mainAxisSize,
crossAxisAlignment: crossAxisAlignment,
textDirection: textDirection,
verticalDirection: verticalDirection,
textBaseline: textBaseline,
);
}
并调用
CustomColumn(children: [
item1,
item2,
item3,
])