在開發(fā)中常常需要一個(gè)懸浮窗口來做各種篩選,實(shí)現(xiàn)懸浮控件需要知道懸浮控件應(yīng)該出現(xiàn)在什么位置以及窗口的大小,而獲取懸浮控件的所需的位置需要知道父控件的position。在flutter 中通過BuildContext findRenderObject獲取widget的position和size。
bool _isShow = false;
OverlayEntry _overlay;
//觸發(fā)事件控件的全局key ,通過key可以獲取到key對應(yīng)的控件
GlobalKey _tapWidget = Globalkey();
OverlayEntry _createSelectViewWithContext(BuildContext context){
//屏幕寬高
RenderBox renderBox = context.findRenderObject();
var screenSize = renderBox.size;
//觸發(fā)事件的控件的位置和大小
renderBox = _tapWidget.findRenderObject();
var parentSize = renderBox.size;
var parentPosition = renderBox.localToGlobal(Offset.zero);
//正式創(chuàng)建Overlay
return OverlayEntry(
builder: (context) => Positioned (
top: parentPosition.dy + parentSize.height,
width: screenSize.width,
height:screenSize.height-parentPosition.dy-parentPosition.height,
child:Stack(
children:<Widget>[
GestureDetctor(//黑色 26透明度背景
onTap:(){
setState( () {
_isShow = false;
});
//點(diǎn)擊背景 隱藏窗口
_showOverlay(_isShow);
},
child: Container(
height: screenSize.height-parentPosition.dy-parentPosition.height,
width:screenSize.width,
color:Colors.black26,
),
),
Container( height:100),//懸浮窗口自定義
]
),
)
);
}
//現(xiàn)實(shí)顯示具體方法 在需要的地方掉用即可
_showOverlay(bool isShow) {
if (isShow) {
_overlay = _createSelectViewWithContext(context);
Overlay.of(context).inset(_overlay);
} else {
_overlay.remove();
}
}