Home > OS >  Extending a Flutter widget with a GestureDetector
Extending a Flutter widget with a GestureDetector

Time:01-31

I'm trying to update my Drawer to a NavigationDrawer that uses NavigationDrawerDestination widgets. 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. 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. Thus, I tried to extend the widget by creating a SidebarDestination like so:

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. 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!" in the console.

How do I correctly implement this?

CodePudding user response:

There are other cases like this tap event win for the inner event.

You can use onPanDown on this case to overcome this situation.

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