Flutter中如何让showMenu在任意屏幕上居中显示?
要解决showMenu无法在所有屏幕上响应式居中的问题,核心是不要用固定数值定位,而是通过屏幕尺寸动态计算位置。
修改后的代码
void _showPopupMenu4() async{ final screenSize = MediaQuery.of(context).size; await showMenu( context: context, // 基于屏幕中心定位菜单 position: RelativeRect.fromCenter( center: Offset(screenSize.width / 2, screenSize.height / 2), width: 220, // 菜单宽度,可根据内容调整 height: 160, // 菜单高度,根据菜单项数量调整 ), items: [ ///2nd item delete button PopupMenuItem( onTap: () { title.value = 'Delete'; }, child: Row( children: [ const Icon( Icons.delete_outline, color: Color.fromRGBO(52, 107, 33, 1), ), SizedBox(width: 15), Text( 'Delete', style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.w400, color: Colors.black, ), ), ], ), ), PopupMenuItem( child: Row( children: [ const Icon( Icons.qr_code_scanner_rounded, color: Color.fromRGBO(52, 107, 33, 1), ), SizedBox(width: 15), Text( 'Scan QR Code', style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.w400, color: Colors.black), ), ], ), ), ], elevation: 4.0, ); }
关键说明
MediaQuery.of(context).size获取当前设备的屏幕宽高,确保在手机、平板等不同尺寸设备上都能拿到准确的屏幕参数RelativeRect.fromCenter是最简洁的居中方式:直接传入屏幕中心的偏移量,再指定菜单的宽高,系统会自动计算出菜单的位置- 菜单的宽高可以根据实际菜单项的内容调整,比如更多菜单项就调高height值,文字较长就调宽width值
内容的提问来源于stack exchange,提问作者Sher Khan Kakar
相关产品推荐
相关产品推荐

