You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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),
// )

关键说明

  1. 严格匹配M3规范:固定高度48dp、圆角16dp,完全对齐Material 3的Extended FAB设计要求。
  2. 自适应宽度:通过SizedBox(width: double.infinity)让按钮自动填满父容器宽度。
  3. 原生级交互体验:用InkWell实现点击水波纹效果,和原生FAB的交互逻辑一致。
  4. 主题适配:通过colorScheme读取应用主题色,按钮样式会自动跟随主题切换。

内容的提问来源于stack exchange,提问作者Vincent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 01:35:15