Search code examples
flutterdartdraggable

How to make Cards draggable in Flutter


I have a list of tasks stored in a 'Todo' type list. I want to iterate over the list and create a card for every item, and I want to be able to drag and reorder these cards on long press.

Here's how I get the today's tasks:

List<Todo> todayTasks = [];
      for (var i = 0; i < _todos.length; i++) {
        if (_todos[i].deadline != null) {
          if (_todos[i].deadline.substring(0, 11) ==
              todayDate.toString().substring(0, 11)) {
            todayTasks.add(_todos[i]);
          }
        }
      }

And here's how I'm creating cards:

for (var todo in todayTasks)
              new Card(
                shadowColor: Colors.black,
                child: ListTile(
                  onTap: () => model.updateTodo(
                      todo.copy(isCompleted: todo.isCompleted == 1 ? 0 : 1)),
                  contentPadding:
                      EdgeInsets.symmetric(horizontal: 0, vertical: 8.0),
                  leading: CircularCheckBox(
                    onChanged: (value) =>
                        model.updateTodo(todo.copy(isCompleted: value ? 1 : 0)),
                    value: todo.isCompleted == 1 ? true : false,
                    materialTapTargetSize: MaterialTapTargetSize.padded,
                  ),
                  trailing: IconButton(
                    icon: Icon(Icons.delete_outline),
                    onPressed: () => model.removeTodo(todo),
                  ),
                  title: Text(
                    todo.name,
                    style: TextStyle(
                      fontSize: 18.0,
                      fontFamily: 'Roboto',
                      fontWeight: FontWeight.w600,
                      color: todo.isCompleted == 1
                          ? Colors.grey[500]
                          : Colors.black,
                      decoration: todo.isCompleted == 1
                          ? TextDecoration.lineThrough
                          : TextDecoration.none,
                    ),
                  ),
                ),
              ),

Solution

  • I have two things for you, with which you can get your desired result:

    • The best thing you can do is to use ReorderableListView class, it is growable. So, you can add items to your list.
    • Another smart way you can opt is, to use packages, which makes your job easier. There is a package for you, named as reorderables 0.3.2

    Please make use of the pointers, and you will be good to go :)