在 Flutter 中创建全宽按钮的 4 种方法
这篇实用且直截了当的文章将引导您了解在 Flutter 中创建全角按钮的 4 种不同方法。
使用 ElevatedButton + Container/SizedBox
将您的ElevatedButton(或TextButton、OutlinedButton)小部件包装在宽度为double.infinity的 Container或SizedBox中。****\
例子:
代码:
Scaffold(
appBar: AppBar(title: const Text('KindaCode.com')),
body: Padding(
padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 10),
child: Column(
children: [
// Full width button 1
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: () {}, child: const Text('Elevated Button'))),
const SizedBox(
height: 20,
),
// Full width button 2
Container(
width: double.infinity,
color: Colors.transparent,
child: OutlinedButton.icon(
onPressed: () {},
icon: const Icon(Icons.add),
label: const Text('Outlined Button')),
),
const SizedBox(
height: 20,
),
// Full width button 3
SizedBox(
width: double.infinity,
child: TextButton.icon(
onPressed: () {},
icon: const Icon(Icons.play_arrow),
label: const Text('Text Button')),
),
],
),
),
)
使用材质按钮
您可以通过将MaterialButton小部件的 minWidth 属性设置为double.infinity来简单地实现一个全角按钮。
例子:
代码:
Scaffold(
appBar: AppBar(title: const Text('KindaCode.com')),
body: Padding(
padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 10),
child: Column(
children: [
MaterialButton(
minWidth: double.infinity,
height: 60,
color: Colors.red,
textColor: Colors.white,
onPressed: () {},
child: const Text('Material Button')),
],
),
),
);
为 ElevatedButton/TextButton 设置 minimumSize
如果您使用 styleFrom 静态方法设置ElevatedButton(或TextButton、OutlinedButton )的样式,则可以通过将 minimumSize参数设置为Size.fromHeight(x) 来使其宽度与父宽度匹配,其中x是按钮的高度。
例子:
代码:
Column(
children: [
ElevatedButton(
style: ElevatedButton.styleFrom(
// The width will be 100% of the parent widget
// The height will be 60
minimumSize: const Size.fromHeight(60)),
onPressed: () {},
child: const Text('Elevated Button')),
const SizedBox(height: 20),
OutlinedButton.icon(
style: OutlinedButton.styleFrom(
// the height is 50, the width is full
minimumSize: const Size.fromHeight(50)),
onPressed: () {},
icon: const Icon(Icons.run_circle),
label: const Text('Outlined Button')),
],
),
使用约束框
例子:
Scaffold(
appBar: AppBar(title: const Text('KindaCode.com')),
body: Padding(
padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 10),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(
minWidth: double.infinity, minHeight: 70),
child: ElevatedButton(
onPressed: () {},
child: const Text('Elevated Button'),
)),
),
),
);
截屏:
总结
我们已经介绍了一系列在 Flutter 中创建全角按钮的技术。从它们中选择您最喜欢的一个并继续使用它。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。