How to make a Chip that handle both onDeleted and tap on it to trigger extra action

179 Views Asked by At

How to make a Chip to support a tap to trigger an action in addition to the onDeleted?

In my code, adding a gesture handler hides onDeleted tap triggering:


 /// A tappable chip
  Widget _tappableChip({
    /// The chip label
    required String label,

    /// Potential badge
    int? badge,

    /// The function to run when a tap occures
    void Function()? onTap,

    /// The function to remove the filter
    void Function()? onDeleted,
  }) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(0, 0, 5, 0),
      child: GestureDetector(
        onTap: onTap,
        child: Chip(
          onDeleted: onDeleted,
          label: Text(label),
          avatar: badge == null ? null : Badge.count(count: badge),
        ),
      ),
    );
  }
4

There are 4 best solutions below

0
Stéphane de Luca On BEST ANSWER

After analysing the Chip.dart library, I came up with a simple solution.

In my build() I use the RawChipwidget instead of the extended Chip class and set the tapEnabled to true as follows:

    return Padding(
      padding: const EdgeInsets.fromLTRB(0, 0, 5, 0),
      child: RawChip(
        onDeleted: onDeleted,
        label: Text(label),
        avatar: badge == null ? null : Badge.count(count: badge),
        tapEnabled: true,
        onPressed: onTap,
      ),
    );
2
Md. Yeasin Sheikh On

You can call both method inside onDelete in _tappableChip

onDeleted: () {
   onDeleted?.call();
   onTap?.call();
  }, // you follow this pattern
0
Buddy On

here i have done some changes in your tappableChip widget

-

Widget _tappableChip({
  required String label,
  int? badge,
  void Function()? onTap,
  void Function()? onDeleted,
}) {
  return Padding(
    padding: const EdgeInsets.fromLTRB(0, 0, 5, 0),
    child: Chip(
      onDeleted: onDeleted,
      label: GestureDetector(
        onTap: onTap, // Handle tap action here
        child: Text(label),
      ),
      avatar: badge == null ? null : Badge.count(count: badge),
    ),
  );
}

and now you can use tappableChip funcation like this -

_tappableChip(
  label: 'Example Chip',
  badge: 3,
  onTap: () {
    // Handle tap action here
    print('Chip tapped');
  },
  onDeleted: () {
    // Handle delete action here
    print('Chip deleted');
  },
),
0
Bawantha On

Chip does not support tap

from doc

  /// If set, this indicates that the chip should be disabled if all of the
  /// tap callbacks ([onSelected], [onPressed]) are null.
  ///
  /// For example, the [Chip] class sets this to false because it can't be
  /// disabled, even if no callbacks are set on it, since it is used for
  /// displaying information only.
  ///
  /// Defaults to true.
  final bool tapEnabled;