如何在Flutter中实现Material 3规范的自适应宽度Extended FAB?
实现Material 3规范的自适应宽度Extended FAB
当然可以实现,你之前用FittedBox的问题在于它会等比例缩放子组件,要么导致按钮高度异常放大,要么限制高度后宽度无法填满容器。正确的做法是通过组件组合自定义符合M3规范的Extended FAB,既能自适应宽度,又能严格遵循Material 3的尺寸与样式标准。
解决方案代码
import 'package:flutter/material.dart'; class FluidExtendedFAB extends StatelessWidget { const FluidExtendedFAB({ super.key, required this.onPressed, required this.label, required this.icon, }); final VoidCallback onPressed; final String label; final Widget icon; @override Widget build(BuildContext context) { final colorScheme = Theme.of(context).colorScheme; return SizedBox( width: double.infinity, height: 48, // Material 3 Extended FAB标准高度 child: InkWell( borderRadius: BorderRadius.circular(16), // M3标准圆角 onTap: onPressed, child: Container( decoration: BoxDecoration( color: colorScheme.primary, borderRadius: BorderRadius.circular(16), ), padding: const EdgeInsets.symmetric(horizontal: 16), alignment: Alignment.center, child: Row( mainAxisSize: MainAxisSize.min, children: [ icon, const SizedBox(width: 8), // 图标与文字间距匹配M3规范 Text( label, style: TextStyle( color: colorScheme.onPrimary, fontSize: 16, fontWeight: FontWeight.w500, ), ), ], ), ), ), ); } } // 使用示例 // FluidExtendedFAB( // onPressed: () {}, // label: 'My button', // icon: const Icon(Icons.add, color: Colors.white), // )
关键说明
- 严格匹配M3规范:固定高度48dp、圆角16dp,完全对齐Material 3的Extended FAB设计要求。
- 自适应宽度:通过
SizedBox(width: double.infinity)让按钮自动填满父容器宽度。 - 原生级交互体验:用
InkWell实现点击水波纹效果,和原生FAB的交互逻辑一致。 - 主题适配:通过
colorScheme读取应用主题色,按钮样式会自动跟随主题切换。
内容的提问来源于stack exchange,提问作者Vincent
相关产品推荐
相关产品推荐

