1.可悬浮的控件Overlay
加入到屏幕中 Overlay.of(context).insert(overlayEntry);
移除 overlayEntry.remove();
2.可拖动.
Draggable拖动拿到offset,setstate()改变Positioned位置
以下 伪代码
OverlayEntry overlayEntry;
double overlayWidth = 50;
Offset offset = Offset.zero;
@override
Widget build(BuildContext context) {
return 可点击控件,点击clickShow;
}
clickShow(){
if (overlayEntry != null) {
return;
}
overlayEntry = _showOverlay();
//往Overlay中插入插入OverlayEntry
Overlay.of(context).insert(overlayEntry);
}
OverlayEntry _showOverlay() {
OverlayEntry overlayEntry = new OverlayEntry(builder: (context) {
//外层使用Positioned进行定位,控制在Overlay中的位置
// 控制不可拖出屏幕外
double dx = 0.0;
double dy = 0.0;
if ((offset.dx > 0) &&
((offset.dx + overlayWidth) < ScreenUtil().screenWidth)) {
dx = offset.dx;
} else if ((offset.dx + overlayWidth) >= ScreenUtil().screenWidth) {
dx = ScreenUtil().screenWidth - overlayWidth;
} else {
dx = 0;
}
if ((offset.dy > 0) &&
((offset.dy + overlayWidth) < ScreenUtil().screenHeight)) {
dy = offset.dy;
} else if ((offset.dy + overlayWidth) >= ScreenUtil().screenHeight) {
dy = ScreenUtil().screenWidth - overlayWidth;
} else {
dy = 0;
}
return new Positioned(
top: dy,
left: dx,
child: Draggable(
feedback: _contentBody(),
child: _contentBody(),
childWhenDragging: Container(), //拖动过程回调
onDraggableCanceled: (Velocity velocity, Offset offset) {
setState(() {
//第二个参数为拖动的动态坐标
this.offset = offset;
});
},
),
);
});
return overlayEntry;
}
Widget _contentBody() {
return Container(
color: Colors.red,
width: overlayWidth,
height: overlayWidth,
);
}
@override
void dispose() {
overlayEntry.remove();//移除
overlayEntry = null;
super.dispose();
}