简体   繁体   English

使用 GestureDetector 扩展 Flutter 小部件

[英]Extending a Flutter widget with a GestureDetector

I'm trying to update my Drawer to a NavigationDrawer that uses NavigationDrawerDestination widgets.我正在尝试将我的Drawer更新为使用NavigationDrawer小部件的NavigationDrawerDestination However, I'm very unhappy with the fact that NavigationDrawerDestinaion 's do not have a callback function. The onDestinationSelected function only takes the index of the destination, and nothing else, for handling taps.但是,我对NavigationDrawerDestinaion没有回调 function 这一事实感到非常不满意onDestinationSelected function 仅采用目的地的索引,没有其他用于处理水龙头。 In my Drawer this is cumbersome as for some users the amount and order of destinations varies.在我的抽屉中,这对于某些用户来说很麻烦,因为目的地的数量和顺序各不相同。

I cannot wrap the NavigationDrawerDestination in a GestureDetector directly as Flutter expects the parent of a NavigationDrawerDestination to be a NavigationDrawer .我不能将NavigationDrawerDestination直接包装在GestureDetector中,因为 Flutter 期望NavigationDrawer NavigationDrawerDestination Thus, I tried to extend the widget by creating a SidebarDestination like so:因此,我尝试通过创建SidebarDestination来扩展小部件,如下所示:

class SidebarDestination extends NavigationDrawerDestination {
  const SidebarDestination({
    super.key,
    required super.icon,
    required super.label,
    super.selectedIcon,
    required this.onTap,
  });

  final void Function() onTap;

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

A complete code example is available in this DartPad .此 DartPad中提供了完整的代码示例。 This no longer raises errors from the framework.这不再引发框架错误。 However, the GestureDetector in my extension widget does not fire: tapping the destination does not print "This is not printed."但是,我的扩展小部件中的 GestureDetector 不会触发:点击目标不会打印“This is not printed.”。 in the console.在控制台中。

How do I correctly implement this?我该如何正确实施呢?

There are other cases like this tap event win for the inner event.还有其他情况,例如这个点击事件赢得了内部事件。

You can use onPanDown on this case to overcome this situation.您可以在这种情况下使用onPanDown来克服这种情况。

 return GestureDetector(
    onPanDown:(_)=> onTap(),

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

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