Search code examples
flutterdraggableflutter-widget

How to show Icon when I started dragging a Widget in Flutter


I want to know how can I show at the bottom of the screen a delete icon when I start dragging a Container in LongPressDraggable widget

Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () => _onTap(context),
        child: LongPressDraggable(
          data: index,
          maxSimultaneousDrags: 1,
          onDragUpdate: (details) => print('update'),
          onDragStarted: () => _buildDragTarget(),
          onDragEnd: (_) => print('end'),
          feedback: Material(
            child: Container(
              height: Sizes.height / 4.5,
              width: Sizes.height / 4.5,
              child: _DraggableContent(
                index: index,
                place: place,
              ),
            ),
          ),
          childWhenDragging: Container(color: Colors.transparent),
          child: _DraggableContent(
            index: index,
            place: place,
          ),
        ));
  }

 Widget _buildDragTarget() {
    return DragTarget<int>(
      builder: (BuildContext context, List<int> data, List<dynamic> rejects) {
        return Icon(Icons.delete);
      },
      onAcceptWithDetails: (DragTargetDetails<int> dragTargetDetails) {
        print('onAcceptWithDetails');
        print('Data: ${dragTargetDetails.data}');
        print('Offset: ${dragTargetDetails.offset}');
      },
    );
  }

At the moment, when I start dragging the item, anything happens and I don't know how to continue


Solution

  • You have an example with Dragable widget here : https://blog.logrocket.com/drag-and-drop-ui-elements-in-flutter-with-draggable-and-dragtarget/

    On the DROPPING AN ITEM part https://blog.logrocket.com/drag-and-drop-ui-elements-in-flutter-with-draggable-and-dragtarget/#:~:text=the%20tomato%20image.-,Dropping%20an%20item,-At%20this%20point

    You need to use the onAccept event on your DragTarget widget :

    onAccept: (data) {
    setState(() {
      showSnackBarGlobal(context, 'Dropped successfully!');
      _isDropped = true;
    });
    },
    

    And on Drag starting, you can show up your delete icon by using this event (https://blog.logrocket.com/drag-and-drop-ui-elements-in-flutter-with-draggable-and-dragtarget/#:~:text=Listening%20to%20drag%20events) :

    onDragStarted: () {
    showSnackBarGlobal(context, 'Drag started');
    },
    

    I hope it will help you