建立一個可擴充套件的 FAB
浮動操作按鈕 (FAB) 是一個浮動在內容區域右下角附近的圓形按鈕。此按鈕代表相應內容的主要操作,但有時,並沒有主要操作。而是,使用者可能需要執行幾個關鍵操作。在這種情況下,您可以建立一個可展開的 FAB,如以下圖所示。按下此可展開 FAB 時,它會彈出多個其他操作按鈕。每個按鈕對應一個關鍵操作。
以下動畫展示了應用程式的行為

建立 ExpandableFab 小部件
#首先建立一個名為 ExpandableFab 的新狀態化小部件。此小部件顯示主要 FAB 並協調其他操作按鈕的展開和摺疊。該小部件接受引數,用於指定 ExpandedFab 是否開始時處於展開狀態,每個操作按鈕的最大距離,以及子項列表。稍後您將使用此列表來提供其他操作按鈕。
@immutable
class ExpandableFab extends StatefulWidget {
const ExpandableFab({
super.key,
this.initialOpen,
required this.distance,
required this.children,
});
final bool? initialOpen;
final double distance;
final List<Widget> children;
@override
State<ExpandableFab> createState() => _ExpandableFabState();
}
class _ExpandableFabState extends State<ExpandableFab> {
@override
Widget build(BuildContext context) {
return const SizedBox();
}
}FAB 交叉淡入淡出
#ExpandableFab 在摺疊時顯示藍色編輯按鈕,在展開時顯示白色關閉按鈕。展開和摺疊時,這兩個按鈕會相互縮放和淡入淡出。
實現兩個不同 FAB 之間的展開和摺疊交叉淡入淡出。
class _ExpandableFabState extends State<ExpandableFab> {
bool _open = false;
@override
void initState() {
super.initState();
_open = widget.initialOpen ?? false;
}
void _toggle() {
setState(() {
_open = !_open;
});
}
@override
Widget build(BuildContext context) {
return SizedBox.expand(
child: Stack(
alignment: Alignment.bottomRight,
clipBehavior: Clip.none,
children: [_buildTapToCloseFab(), _buildTapToOpenFab()],
),
);
}
Widget _buildTapToCloseFab() {
return SizedBox(
width: 56,
height: 56,
child: Center(
child: Material(
shape: const CircleBorder(),
clipBehavior: Clip.antiAlias,
elevation: 4,
child: InkWell(
onTap: _toggle,
child: Padding(
padding: const EdgeInsets.all(8),
child: Icon(Icons.close, color: Theme.of(context).primaryColor),
),
),
),
),
);
}
Widget _buildTapToOpenFab() {
return IgnorePointer(
ignoring: _open,
child: AnimatedContainer(
transformAlignment: Alignment.center,
transform: Matrix4.diagonal3Values(
_open ? 0.7 : 1.0,
_open ? 0.7 : 1.0,
1.0,
),
duration: const Duration(milliseconds: 250),
curve: const Interval(0.0, 0.5, curve: Curves.easeOut),
child: AnimatedOpacity(
opacity: _open ? 0.0 : 1.0,
curve: const Interval(0.25, 1.0, curve: Curves.easeInOut),
duration: const Duration(milliseconds: 250),
child: FloatingActionButton(
onPressed: _toggle,
child: const Icon(Icons.create),
),
),
),
);
}
}開啟按鈕與關閉按鈕疊加在 Stack 中,允許頂部按鈕出現和消失時出現交叉淡入淡出的視覺效果。
為了實現交叉淡入淡出動畫,開啟按鈕使用帶有縮放變換 (scale transform) 和 AnimatedOpacity 的 AnimatedContainer。當 ExpandableFab 從摺疊狀態變為展開狀態時,開啟按鈕會縮小並淡出。然後,當 ExpandableFab 從展開狀態變為摺疊狀態時,開啟按鈕會放大並淡入。
您會注意到開啟按鈕被 IgnorePointer 小部件包裹。這是因為開啟按鈕始終存在,即使它是透明的。如果沒有 IgnorePointer,即使關閉按鈕可見,開啟按鈕也始終接收點選事件。
建立 ActionButton 小部件
#從 ExpandableFab 展開的每個按鈕都具有相同的設計。它們是帶有白色圖示的藍色圓圈。更準確地說,按鈕背景色是 ColorScheme.secondary 顏色,圖示顏色是 ColorScheme.onSecondary。
定義一個名為 ActionButton 的新無狀態小部件來顯示這些圓形按鈕。
@immutable
class ActionButton extends StatelessWidget {
const ActionButton({super.key, this.onPressed, required this.icon});
final VoidCallback? onPressed;
final Widget icon;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Material(
shape: const CircleBorder(),
clipBehavior: Clip.antiAlias,
color: theme.colorScheme.secondary,
elevation: 4,
child: IconButton(
onPressed: onPressed,
icon: icon,
color: theme.colorScheme.onSecondary,
),
);
}
}將此新 ActionButton 小部件的幾個例項傳遞到您的 ExpandableFab 中。
floatingActionButton: ExpandableFab(
distance: 112,
children: [
ActionButton(
onPressed: () => _showAction(context, 0),
icon: const Icon(Icons.format_size),
),
ActionButton(
onPressed: () => _showAction(context, 1),
icon: const Icon(Icons.insert_photo),
),
ActionButton(
onPressed: () => _showAction(context, 2),
icon: const Icon(Icons.videocam),
),
],
),展開和摺疊操作按鈕
#子 ActionButton 在展開時應從開啟的 FAB 下方飛出。然後,在摺疊時,子 ActionButton 應飛回開啟的 FAB 下方。此運動需要顯式設定每個 ActionButton 的 (x,y) 位置,以及一個 Animation 來編排這些 (x,y) 位置隨時間的變化。
引入一個 AnimationController 和一個 Animation 來控制各種 ActionButton 擴充套件和摺疊的速率。
class _ExpandableFabState extends State<ExpandableFab>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<double> _expandAnimation;
bool _open = false;
@override
void initState() {
super.initState();
_open = widget.initialOpen ?? false;
_controller = AnimationController(
value: _open ? 1.0 : 0.0,
duration: const Duration(milliseconds: 250),
vsync: this,
);
_expandAnimation = CurvedAnimation(
curve: Curves.fastOutSlowIn,
reverseCurve: Curves.easeOutQuad,
parent: _controller,
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _toggle() {
setState(() {
_open = !_open;
if (_open) {
_controller.forward();
} else {
_controller.reverse();
}
});
}
}接下來,引入一個名為 _ExpandingActionButton 的新無狀態小部件,並配置此小部件來為單個 ActionButton 設定動畫和定位。ActionButton 以一個通用的 Widget 形式的 child 提供。
@immutable
class _ExpandingActionButton extends StatelessWidget {
const _ExpandingActionButton({
required this.directionInDegrees,
required this.maxDistance,
required this.progress,
required this.child,
});
final double directionInDegrees;
final double maxDistance;
final Animation<double> progress;
final Widget child;
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: progress,
builder: (context, child) {
final offset = Offset.fromDirection(
directionInDegrees * (math.pi / 180.0),
progress.value * maxDistance,
);
return Positioned(
right: 4.0 + offset.dx,
bottom: 4.0 + offset.dy,
child: Transform.rotate(
angle: (1.0 - progress.value) * math.pi / 2,
child: child!,
),
);
},
child: FadeTransition(opacity: progress, child: child),
);
}
}_ExpandingActionButton 中最重要的部分是 Positioned 小部件,它在周圍的 Stack 中將 child 定位到特定的 (x,y) 座標。AnimatedBuilder 會在每次動畫更改時重建 Positioned 小部件。FadeTransition 小部件負責協調每個 ActionButton 在展開和摺疊時的出現和消失。
最後,在 ExpandableFab 中使用新的 _ExpandingActionButton 小部件來完成練習。
class _ExpandableFabState extends State<ExpandableFab>
with SingleTickerProviderStateMixin {
@override
Widget build(BuildContext context) {
return SizedBox.expand(
child: Stack(
alignment: Alignment.bottomRight,
clipBehavior: Clip.none,
children: [
_buildTapToCloseFab(),
..._buildExpandingActionButtons(),
_buildTapToOpenFab(),
],
),
);
}
List<Widget> _buildExpandingActionButtons() {
final children = <Widget>[];
final count = widget.children.length;
final step = 90.0 / (count - 1);
for (
var i = 0, angleInDegrees = 0.0;
i < count;
i++, angleInDegrees += step
) {
children.add(
_ExpandingActionButton(
directionInDegrees: angleInDegrees,
maxDistance: widget.distance,
progress: _expandAnimation,
child: widget.children[i],
),
);
}
return children;
}
}恭喜!您現在擁有了一個可展開的 FAB。
互動示例
#執行應用
- 點選右下角的 FAB,它顯示一個編輯圖示。它會展開成 3 個按鈕,並且 FAB 本身被一個關閉按鈕(顯示為 X)替換。
- 點選關閉按鈕,可以看到展開的按鈕飛回原始 FAB,並且 X 被編輯圖示替換。
- 再次展開 FAB,然後點選任意一個衛星按鈕,您將看到一個顯示該按鈕操作的對話方塊。
import 'dart:math' as math;
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: ExampleExpandableFab(),
debugShowCheckedModeBanner: false,
),
);
}
@immutable
class ExampleExpandableFab extends StatelessWidget {
static const _actionTitles = ['Create Post', 'Upload Photo', 'Upload Video'];
const ExampleExpandableFab({super.key});
void _showAction(BuildContext context, int index) {
showDialog<void>(
context: context,
builder: (context) {
return AlertDialog(
content: Text(_actionTitles[index]),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('CLOSE'),
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Expandable Fab')),
body: ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: 25,
itemBuilder: (context, index) {
return FakeItem(isBig: index.isOdd);
},
),
floatingActionButton: ExpandableFab(
distance: 112,
children: [
ActionButton(
onPressed: () => _showAction(context, 0),
icon: const Icon(Icons.format_size),
),
ActionButton(
onPressed: () => _showAction(context, 1),
icon: const Icon(Icons.insert_photo),
),
ActionButton(
onPressed: () => _showAction(context, 2),
icon: const Icon(Icons.videocam),
),
],
),
);
}
}
@immutable
class ExpandableFab extends StatefulWidget {
const ExpandableFab({
super.key,
this.initialOpen,
required this.distance,
required this.children,
});
final bool? initialOpen;
final double distance;
final List<Widget> children;
@override
State<ExpandableFab> createState() => _ExpandableFabState();
}
class _ExpandableFabState extends State<ExpandableFab>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<double> _expandAnimation;
bool _open = false;
@override
void initState() {
super.initState();
_open = widget.initialOpen ?? false;
_controller = AnimationController(
value: _open ? 1.0 : 0.0,
duration: const Duration(milliseconds: 250),
vsync: this,
);
_expandAnimation = CurvedAnimation(
curve: Curves.fastOutSlowIn,
reverseCurve: Curves.easeOutQuad,
parent: _controller,
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _toggle() {
setState(() {
_open = !_open;
if (_open) {
_controller.forward();
} else {
_controller.reverse();
}
});
}
@override
Widget build(BuildContext context) {
return SizedBox.expand(
child: Stack(
alignment: Alignment.bottomRight,
clipBehavior: Clip.none,
children: [
_buildTapToCloseFab(),
..._buildExpandingActionButtons(),
_buildTapToOpenFab(),
],
),
);
}
Widget _buildTapToCloseFab() {
return SizedBox(
width: 56,
height: 56,
child: Center(
child: Material(
shape: const CircleBorder(),
clipBehavior: Clip.antiAlias,
elevation: 4,
child: InkWell(
onTap: _toggle,
child: Padding(
padding: const EdgeInsets.all(8),
child: Icon(Icons.close, color: Theme.of(context).primaryColor),
),
),
),
),
);
}
List<Widget> _buildExpandingActionButtons() {
final children = <Widget>[];
final count = widget.children.length;
final step = 90.0 / (count - 1);
for (
var i = 0, angleInDegrees = 0.0;
i < count;
i++, angleInDegrees += step
) {
children.add(
_ExpandingActionButton(
directionInDegrees: angleInDegrees,
maxDistance: widget.distance,
progress: _expandAnimation,
child: widget.children[i],
),
);
}
return children;
}
Widget _buildTapToOpenFab() {
return IgnorePointer(
ignoring: _open,
child: AnimatedContainer(
transformAlignment: Alignment.center,
transform: Matrix4.diagonal3Values(
_open ? 0.7 : 1.0,
_open ? 0.7 : 1.0,
1.0,
),
duration: const Duration(milliseconds: 250),
curve: const Interval(0.0, 0.5, curve: Curves.easeOut),
child: AnimatedOpacity(
opacity: _open ? 0.0 : 1.0,
curve: const Interval(0.25, 1.0, curve: Curves.easeInOut),
duration: const Duration(milliseconds: 250),
child: FloatingActionButton(
onPressed: _toggle,
child: const Icon(Icons.create),
),
),
),
);
}
}
@immutable
class _ExpandingActionButton extends StatelessWidget {
const _ExpandingActionButton({
required this.directionInDegrees,
required this.maxDistance,
required this.progress,
required this.child,
});
final double directionInDegrees;
final double maxDistance;
final Animation<double> progress;
final Widget child;
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: progress,
builder: (context, child) {
final offset = Offset.fromDirection(
directionInDegrees * (math.pi / 180.0),
progress.value * maxDistance,
);
return Positioned(
right: 4.0 + offset.dx,
bottom: 4.0 + offset.dy,
child: Transform.rotate(
angle: (1.0 - progress.value) * math.pi / 2,
child: child!,
),
);
},
child: FadeTransition(opacity: progress, child: child),
);
}
}
@immutable
class ActionButton extends StatelessWidget {
const ActionButton({super.key, this.onPressed, required this.icon});
final VoidCallback? onPressed;
final Widget icon;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Material(
shape: const CircleBorder(),
clipBehavior: Clip.antiAlias,
color: theme.colorScheme.secondary,
elevation: 4,
child: IconButton(
onPressed: onPressed,
icon: icon,
color: theme.colorScheme.onSecondary,
),
);
}
}
@immutable
class FakeItem extends StatelessWidget {
const FakeItem({super.key, required this.isBig});
final bool isBig;
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 24),
height: isBig ? 128 : 36,
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(8)),
color: Colors.grey.shade300,
),
);
}
}