如何在 Flutter 中使 Cards 可拖动

How to make Cards draggable in Flutter

我有一个存储在 'Todo' 类型列表中的任务列表。我想遍历列表并为每个项目创建一张卡片,我希望能够在长按时拖动这些卡片并对其重新排序。

以下是我如何获得今天的任务:

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]);
          }
        }
      }

下面是我创建卡片的方式:

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,
                    ),
                  ),
                ),
              ),

我有两件事要告诉你,你可以用它们得到你想要的结果:

  • 你能做的最好的事情就是使用 ReorderableListView class,它是可以增长的。因此,您可以将项目添加到列表中。
  • 您可以选择的另一种聪明方法是使用包,这可以使您的工作更轻松。有一个包裹给你,命名为 reorderables 0.3.2

请多多指教,万事大吉:)