Flutter Web中如何计算屏幕底部到指定Widget的距离?
计算屏幕与Container的距离
当然可以分别计算屏幕顶部/底部到Container的距离,你已经实现了顶部距离的计算,在此基础上就能轻松得到底部相关的距离:
步骤1:获取屏幕总高度
通过MediaQuery获取当前屏幕的完整高度:
double screenHeight = MediaQuery.of(context).size.height;
步骤2:补充获取Container自身高度
基于你已有的代码,从RenderBox中取出Container的高度:
RenderBox box = keyGlobal.currentContext!.findRenderObject() as RenderBox; Offset position = box.localToGlobal(Offset.zero); double topToContainerTop = position.dy; // 屏幕顶部到Container顶部的距离 double containerHeight = box.size.height; // Container自身的高度
步骤3:计算屏幕底部到Container的距离
分两种常见场景:
- 屏幕底部到Container顶部的距离:
double bottomToContainerTop = screenHeight - topToContainerTop; - 屏幕底部到Container底部的距离:
double bottomToContainerBottom = screenHeight - (topToContainerTop + containerHeight);
注意要确保keyGlobal已正确绑定到目标Container,并且在组件完成渲染后执行计算(比如放在WidgetsBinding.instance.addPostFrameCallback回调里,避免context未初始化的问题)。
内容的提问来源于stack exchange,提问作者Developer
相关产品推荐
相关产品推荐

