import 'package:flutter/material.dart'; void main2() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp(home: DragIconDemo()); } } class DragIconDemo extends StatefulWidget { @override _DragIconDemoState createState() => _DragIconDemoState(); } class _DragIconDemoState extends State { // 跟踪图标在哪个容器中(1或2) int iconContainer = 1; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('图标拖拽示例')), body: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ // 第一个容器 buildContainer( containerNumber: 1, child: iconContainer == 1 ? buildDraggableIcon() : null, ), // 第二个容器 buildContainer( containerNumber: 2, child: iconContainer == 2 ? buildDraggableIcon() : null, ), ], ), ); } // 构建可拖拽图标 Widget buildDraggableIcon() { return Draggable( data: iconContainer, // 传递当前容器编号作为数据 feedback: const Icon(Icons.star, size: 50, color: Colors.amber), childWhenDragging: const Opacity( opacity: 0.5, child: Icon(Icons.star, size: 50, color: Colors.amber), ), child: const Icon(Icons.star, size: 50, color: Colors.amber), ); } // 构建容器(同时也是拖放目标) Widget buildContainer({required int containerNumber, Widget? child}) { return DragTarget( builder: (context, candidateData, rejectedData) { return Container( width: 150, height: 150, decoration: BoxDecoration( border: Border.all(color: Colors.blue, width: 2), borderRadius: BorderRadius.circular(10), ), child: Center(child: child), ); }, onWillAcceptWithDetails: (data) => true, // 接受任何拖拽数据 onAcceptWithDetails: (data) { setState(() { iconContainer = containerNumber; // 更新图标位置 }); }, ); } }