Search code examples
flutteranimationdismissible

FLutter : onHorizontalDragUpdate is not triggered in dismissible widget


I created a dismissible widget like this:

 GestureDetector(
      onHorizontalDragUpdate: (DragUpdateDetails event) {
        setState(() {
          _offsetX = event.globalPosition.dx;
          print("Event : ${event.globalPosition.dx}");
        });
      },
      onHorizontalDragStart: (DragStartDetails event) {
        setState(() {
          _offsetX = event.globalPosition.dx;
          print("Event : ${event.globalPosition.dx}");
        });

        print(_offsetX.abs());
        // }
      },
      child: Dismissible(
        key: UniqueKey(),
        direction: DismissDirection.endToStart,
        onResize: () {},
        onUpdate: (details) {
          // });
        },
        onDismissed: (direction) {},
        secondaryBackground: AnimatedContainer(
            duration: const Duration(milliseconds: 300),
            transform: Matrix4.translationValues(_offsetX - 36, 0.0, 0.0),
            color: Colors.red,
            padding: const EdgeInsets.only(left: 20),
            child: const Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Icon(
                  Icons.delete,
                  color: Colors.white,
                  size: 36,
                ),
                // Add other widgets here that you want to move with the swipe
              ],
            )),
        background: Container(
          color: DsColors.secondary,
        ),
        confirmDismiss: (direction) async {
          final result = await Future.delayed(const Duration(seconds: 6), () {
            return false;
          });
          return result;
        },
        child: widget.child,
      ),
    )

I want to when the child is swapped, delete the icon inside secondaryBackground to move from right to left like a swapped child, but when I swap the child onHorizontalDragUpdate won't be triggered?


Solution

  • Instead of using onHorizontalDragUpdate from GestureDetector, you can get similar drag update information from the onUpdate callback of the Dismissible.

    Dismissible(
      onUpdate: (details) {
        final progress = details.progress;
        // ...
      }
    )
    

    You would also need to pass a key that persists between build calls but is unique to the item. Instead of using UniqueKey() that is constructed in time, you should use a ValueKey with a constant value or appended with the item identifier. For example, if the widget is inside a ListView builder, you would need to include the index in the ValueKey's value:

    Dismissible(
      key: ValueKey('myItem-$index'),
      // ...
    )