我需要在DragTarget.onMove
中获得可拖动的位置。但是在DragTargetDetails.offset
中,我们有一些奇怪的值。在源代码中,我看到它被设置为avatar._lastOffset
,即globalPosition - dragStartPoint
。但我无法访问这些来计算DragTarget内部的全局位置或局部位置。文档中说DragTargetDetails.offset
是"当特定指针事件发生在可拖动对象上时的全局位置"。但实际上,它是一个全球位置减去开始麻醉点,这似乎是无用的,我怎么能使用这个值?
我准备了一个简单的例子,在这里你可以看到Draggable.onDragUpdate
(这是真正的全局位置)和DragTarget.onMove
的偏移量。
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Offset _dragUpdateOffset = Offset.zero;
Offset _moveOffset = Offset.zero;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Draggable(
data: "Test Data",
child: const Text("Drag me"),
feedback: const Material(child:Text("Draggable")),
childWhenDragging: Container(),
onDragUpdate: (details) {
setState(() {
_dragUpdateOffset = details.globalPosition;
});
},
),
),
body: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text("dragUpdate: ${_dragUpdateOffset.dx},${_dragUpdateOffset.dy}"),
const Text("vs"),
Text("onMove: ${_moveOffset.dx},${_moveOffset.dy}")
],),
Expanded(
child: Center(
child: DragTarget(
onMove: (details) {
_moveOffset = details.offset;
},
onWillAccept: (data) => true,
builder: (context, candidateData, rejectedData) => SizedBox(
width: 100,
height: 100,
child: Container(
child: const Text("DragTarget"),
decoration: const BoxDecoration(color: Colors.green),
),
),
),
),
),
],
),
);
}
}
尝试将Draggable与Listener包裹起来,并使用"onPointerMove: (details)"