间距小部件
Flutter 有很多小部件可以帮助设置间距 - 在 Row 或 Column 等内部小部件中,它们会接收子列表。
F.ex:
-
Spacer - 填充其他子小部件之间空间的小部件。
-
Flexible - 包装一个小部件并允许您定义一个 flex 值以影响该小部件与子列表中的其他小部件相比应占用多少空间。
-
Expanded - 如果你在其中包装一个小部件,你会让一个小部件填满剩余的空间。
-
ConstrainedBox - 允许为子小部件设置 minWidth、maxWidth、minHeight、maxHeight。
代码示例
根据您的要求:
- 单行文本有缩进
- 多行文本没有缩进
SizedBox 是不行的
SizedBox 不适用于多行文本,因为 Row 中的多行 Text 必须包含在 Flexible (Flutter - multiline label inside row) 中,并且 SizedBox 将始终占据您设置的任何宽度- Spacer、Flexible 或 Expanded 的组合似乎在这里不起作用。
替代解决方案
一种选择是指定 Row 并将 mainAxisAlignment 设置为 MainAxisAlignment.end 并使用带有 MediaQuery 的 BoxConstraint 减去我们想要的文本容器的 minWidth 的屏幕宽度。
class IndentedText extends StatelessWidget {
const IndentedText({Key? key, required this.text, this.textMinWidth = 150}) : super(key: key);
final String text;
final double textMinWidth;
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.max,
children: [
Flexible(
child: ConstrainedBox(
constraints: BoxConstraints(minWidth: MediaQuery.of(context).size.width - textMinWidth),
child: Text(text),
),
),
],
);
}
}
然后是widget的用法
class SpacingExample extends StatelessWidget {
const SpacingExample({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Card(
child: Column(
children: const [
IndentedText(text: "text"),
IndentedText(
text:
"A vehicle is a object people use to get around more easily, etc etc make the text longer and multiline.",
)
],
),
),
],
);
}
}
外观:
- 注意:对于更复杂的用例,当您减去 minWidth - 如果布局有多个列 f.ex. 以及可能的填充大小,您可能还需要减去其他小部件的大小。李>