英文:
Wrap with spaceBetween and center
问题
I'm trying to put 2 buttons on the same line, with the maximum horizontal space between them (one button will be at the most left and the other at the most right). But when there's no horizontal space for both, I want them to be displayed centered vertically, one above the other.
When there is enough space:
When there is not enough space:
I've tried the Wrap widget (https://api.flutter.dev/flutter/widgets/Wrap-class.html) in several different ways, but without success.
英文:
I'm trying to put 2 buttons on the same line, with the maximum horizontal space between them (one button will be at the most left and the other at the most right). But when there's no horizontal space for both, I want them to be displayed centered vertically, one above the other.
When there is enough space:
When there is not enough space:
I've tried the Wrap widget (https://api.flutter.dev/flutter/widgets/Wrap-class.html) in several different ways, but without success.
答案1
得分: 1
根据这个链接中的信息这里,对齐是基于最长的行来确定的。我想到的一个(巧妙的)解决方案是添加一个无形的行,它占据了父部件的整个宽度。这将强制换行并启用对齐设置。
Wrap(
alignment: WrapAlignment.spaceBetween,
children: [
const SizedBox(width: double.infinity), // 充满整个宽度的行
Widget1,
Widget2,
],
)
英文:
Per the info in this link here, alignment is based on the longest line. A (hacky) solution I came up with is to add an invisible line that takes the full width of your parent widget. This will force a wrap and bring the alignment setting into play.
Wrap(
alignment: WrapAlignment.spaceBetween,
children: [
const SizedBox(width: double.infinity), // full width line
Widget1,
Widget2,
],
)
答案2
得分: 0
你可以使用以下的代码来实现这个,希望对你有帮助:
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Wrap(
spacing: 16, // 在按钮之间添加间距
alignment: WrapAlignment.center,
children: [
ElevatedButton(
onPressed: () {},
child: const Text('Button 1'),
),
ElevatedButton(
onPressed: () {},
child: const Text('Button 2'),
),
],
),
),
);
}
}
希望这对你有帮助。
英文:
You can use the code below to achieve this, hope this helps:
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Wrap(
spacing: 16, // add spacing between buttons
alignment: WrapAlignment.center,
children: [
ElevatedButton(
onPressed: () {},
child: const Text('Button 1'),
),
ElevatedButton(
onPressed: () {},
child: const Text('Button 2'),
),
],
)),
);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论