繁体   English   中英

在 Flutter 中,我可以使 DropdownButton 的子项成为 DropdownMenuItem 以外的小部件吗

[英]In Flutter can I make the children of a DropdownButton a widget other than DropdownMenuItem

我有一个 Flutter web 应用程序,其中包括一些页面上的 web 视图。

我正在使用PointerInterceptor来防止我的 web 视图吸收点击事件。

这很好用,但我现在有一个情况,我有一个DropdownButton并单击它会创建一堆DropdownMenuItem - 我想将这些项目包装在同一个PointerInterceptor中,如下所示:

DropdownButton<dynamic>(
                items: myItems.map((e) => PointerInterceptor( child: DropdownMenuItem(
                  value: e,
                  child: Text(e.name),
                ))).toList(),

问题是这会导致以下错误:

无法将参数类型“List”分配给参数类型“List<DropdownMenuItem>?”。

但是我已经将我的DropdownButton放在应用栏中,并且DropdownMenuItems直接注入到MaterialApp小部件下的小部件树中,因此我无法包装更高级别的小部件。

当 DropdownButton 期望items为 DropdownMenuItems 时,如何使用 PointerInterceptor 小部件?

我能够通过制作另一个包装DropdownMenuItems的 class 来实现这一点,然后将其用作DropdownButton中的items
(即用PointerInterceptedDropdownMenuItem替换DropdownMenuItems

这是我的包装器 class 的定义:

class PointerInterceptedDropdownMenuItem<T> extends DropdownMenuItem {

  final VoidCallback? onTap;
  final T? value;
  final bool enabled;

  const PointerInterceptedDropdownMenuItem({
    Key? key,
    this.onTap,
    this.value,
    this.enabled = true,
    AlignmentGeometry alignment = AlignmentDirectional.centerStart,
    required Widget child,
  }) : super(key: key, alignment:alignment, child: child);

  @override Widget build(BuildContext context) {
    return PointerInterceptor( child: super.build(context) );
  }
}

注意:对于询问让 DropdownButton 的子项不是 DropdownMenuItem 的问题的部分,这是一个很好、整洁的解决方案,
但对于将项目包装在 PointerInterceptor class 中的特定部分来说,这不是一个好的解决方案,那是因为拥有那么多 PointerInceptors(我有一个长列表)会对性能产生不良影响,因此该部分的解决方案将是将 PointerInterceptor 移动到脚手架的顶层,然后使其成为条件,并更新一些 state(反映打开的下拉列表)以说明 PointerInterceptor 是否应该覆盖整个屏幕。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM