Search code examples
androidflutterdartmobiledraggable

How do I create a Draggable without using DragTarget in Flutter?


I'm a newbie at Flutter. I'm trying to create a Draggable but I don't want to use a DragTarget. I want it to drag and drop wherever I want. When I did that after the drop operation object disappeared. I don't want it to disappear. How can I do that? I checked the resources and YouTube, however, I cannot find anything useful. Thanks in advance.


Solution

  • Following up to my comment, here is a code example. You have a Stack, with your Draggable element, you then rebuild it to the new position using a Positioned widget and an offset. You could also recreate a DragTarget following the same exemple, just repositioning it if you need its features.

    You might need to adapt a bit the offset in order to make it react to your target element size.

    import 'package:flutter/material.dart';
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key? key, required this.title}) : super(key: key);
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      bool _started = false;
      Offset _position = Offset(20, 20);
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: SafeArea(
            child: Stack(
              children: <Widget>[
                Positioned(
                  top: _position.dy - 30, // Size of widget to reposition correctly
                  left: _position.dx,
                  child: Draggable(
                    child: Chip(label: Text('Element')),
                    feedback: Material(
                        child: Chip(
                      label: Text('Element'),
                    )),
                    onDragEnd: (details) {
                      print(details.offset);
                      setState(() {
                        if (!_started) _started = true;
                        _position = details.offset;
                      });
                    },
                  ),
                ),
              ],
            ),
          ),
        );
      }
    }