使用 Flutter 的 Draggable 和 DragTarget 实现拖拽交互

961 阅读1分钟

在 Flutter 中,Draggable 和 DragTarget 是两个强大的组件,它们共同提供了拖拽交互的功能。Draggable 组件允许用户拖拽一个可交互的元素,而 DragTarget 组件则接收被拖拽的元素,并触发相应的操作。本文将详细介绍如何使用 Flutter 的 Draggable 和 DragTarget 组件来实现拖拽交互。

1. 引入 Draggable 和 DragTarget 组件

首先,我们需要在 Flutter 项目中引入 Draggable 和 DragTarget 组件。添加以下依赖项:

import 'package:flutter/material.dart';

2. 创建 Draggable 和 DragTarget 组件

class DraggableExample extends StatefulWidget {
  const DraggableExample({super.key});

  @override
  State<DraggableExample> createState() => _DraggableExampleState();
}

class _DraggableExampleState extends State<DraggableExample> {
  int acceptedData = 0;

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Draggable<int>(
            maxSimultaneousDrags: 1,
            // Data is the value this Draggable stores.
            data: 10,
            feedback: Container(
              color: Colors.deepOrange,
              height: 100,
              width: 100,
              child: const Icon(Icons.directions_run),
            ),
            childWhenDragging: Container(
              height: 100.0,
              width: 100.0,
              color: Colors.pinkAccent,
              child: const Center(
                child: Text('Child When Dragging'),
              ),
            ),
            child: Container(
              height: 100.0,
              width: 100.0,
              color: Colors.lightGreenAccent,
              child: const Center(
                child: Text('Draggable'),
              ),
            ),
          ),
          DragTarget<int>(
            builder: (
                BuildContext context,
                List<dynamic> accepted,
                List<dynamic> rejected,
                ) {
              return Container(
                height: 100.0,
                width: 100.0,
                color: Colors.cyan,
                child: Center(
                  child: Text('Value is updated to: $acceptedData'),
                ),
              );
            },
            onAccept: (int data) {
              setState(() {
                acceptedData += data;
              });
            },
          ),
        ],
      ),
    );
  }
}

在上面的示例中,我们将 Draggable 和 DragTarget 组件嵌入到一个页面中。

image.png

拖动时候的会显示feedback的Widget样式。

image.png

拖拽 Draggable 组件,并将其释放在 DragTarget 组件上。DragTarget 组件将接收并显示被拖拽的数据。每次释放acceptedData都会加上data的数据。

image.png

相似Widget

  • LongPressDraggable

希望本文能帮助你理解和使用 Flutter 的 Draggable 和 DragTarget 组件来实现拖拽交互。你可以根据自己的项目需求进行进一步的定制和扩展。享受 Flutter 编程的乐趣吧!