如何为Flutter中的MenuAnchor菜单添加滚动条?
要给MenuAnchor的可滚动菜单添加滚动条,你需要正确结合Scrollbar和ListView,同时避免布局冲突。以下是可行的解决方案:
修正后的代码
Row( children: [ Container( width: widget.rowWidth / 2, child: const Text("Row Title") ), SizedBox( width: widget.rowWidth / 2, child: MenuAnchor( style: MenuStyle( maximumSize: MaterialStateProperty.resolveWith((states) => const Size.fromHeight(256)), ), menuChildren: [ Scrollbar( thumbVisibility: true, // 强制显示滚动条,也可设置为false让其仅在滚动时出现 child: ListView.builder( shrinkWrap: true, // 让ListView根据内容收缩高度,适配MenuAnchor的最大高度限制 primary: false, // 禁用默认滚动控制器,避免和MenuAnchor内部滚动机制冲突 itemCount: _menuList.length, itemBuilder: (context, index) => MenuItemButton( onPressed: () { // 菜单选项点击逻辑 MenuAnchor.of(context).close(); }, child: SizedBox( width: widget.rowWidth / 2 - _offset, child: Text(_menuList[index]), // 移除不必要的Expanded,避免布局异常 ), ), ), ), ], builder: (context, controller, child) => Padding( padding: const EdgeInsets.all(16), child: TextButton( onPressed: () { controller.isOpen ? controller.close() : controller.open(); }, child: const Text("Add") ), ), ), ), ], )
关键说明
shrinkWrap: true:让ListView仅占用内容所需高度,同时受MenuAnchor的maximumSize限制,超过最大高度时自动触发滚动。primary: false:禁用ListView的默认滚动控制器,避免和MenuAnchor内部的滚动逻辑冲突,防止页面冻结。itemCount:必须指定列表项数量,否则ListView无法正确渲染内容,这是你之前代码导致页面冻结的核心原因之一。- 移除
Expanded:原代码中Expanded嵌套在SizedBox内会导致布局约束冲突,直接使用Text即可适配指定宽度。
内容的提问来源于stack exchange,提问作者Tatry Project
相关产品推荐
相关产品推荐

