在 Flutter 中实现悬浮 Widget 主要有以下几种方法:
1. Stack + Positioned(最常用)
Stack(
children: <Widget>[
// 主内容
Container(color: Colors.white),
// 悬浮 Widget
Positioned(
right: 20,
bottom: 20,
child: FloatingActionButton(
onPressed: () {},
child: Icon(Icons.add),
),
),
],
)
2. FloatingActionButton(官方悬浮按钮)
Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {},
child: Icon(Icons.add),
),
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
)
3. Overlay(全局悬浮)
// 显示悬浮层
void _showOverlay() {
OverlayState overlayState = Overlay.of(context);
overlayState.insert(OverlayEntry(
builder: (context) => Positioned(
top: 100,
right: 20,
child: Material(
child: Container(
padding: EdgeInsets.all(16),
color: Colors.blue,
child: Text('悬浮提示'),
),
),
),
));
}
4. Draggable(可拖拽悬浮)
Draggable(
child: Container(
width: 100,
height: 100,
color: Colors.red,
child: Center(child: Text('拖拽我')),
),
feedback: Container(
width: 100,
height: 100,
color: Colors.red.withOpacity(0.5),
child: Center(child: Text('拖拽中')),
),
childWhenDragging: Container(),
)
完整示例
class FloatingWidgetExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
// 页面内容
ListView.builder(
itemCount: 20,
itemBuilder: (context, index) => ListTile(
title: Text('项目 $index'),
),
),
// 悬浮按钮
Positioned(
bottom: 20,
right: 20,
child: FloatingActionButton(
onPressed: () {},
child: Icon(Icons.chat),
),
),
],
),
);
}
}
总结:
- 简单悬浮使用
Stack + Positioned
- 按钮类使用
FloatingActionButton
- 全局悬浮使用
Overlay
- 可拖拽使用
Draggable
选择哪种方式取决于具体需求和交互场景。