I have a draggable like such (a is a StatefulWidget
):
Draggable(child: a, feedback: a, childWhenDragging: null, data: a)
However, a
has a GlobalKey in an effort to preserve state when the widget is dropped. My issue is that when you attempt to drag, a duplicate GlobalKey
error is thrown (probably because child
and feedback
exist on the same frame). Is there any way to achieve this behavior without any errors?
Reproducible example:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class SFWidget extends StatefulWidget {
const SFWidget({Key? key}) : super(key: key);
@override
State<SFWidget> createState() => SFWidgetState();
}
class SFWidgetState extends State<SFWidget> {
String str = "str";
@override
Widget build(BuildContext context) {
return Text(str);
}
void edit(String newstr) {
setState(() {
str = newstr;
});
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final key = GlobalKey<SFWidgetState>();
final widget = SFWidget(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Draggable(
child: widget,
feedback: widget,
data: widget,
childWhenDragging: null,
),
);
}
}
CodePudding user response:
The problem is that the same widget stays in the starting place if childWhenDragging
is null
. From the official docs:
If
childWhenDragging
isnull
, then theDraggable
widget will always display child (and so the drag source representation will not change while a drag is underway).
So, to fix it just default the childWhenDragging
to something that does nothing like Container()
. Something like below:
...
body: Draggable(
child: widget,
feedback: widget,
data: widget,
childWhenDragging: Container(), // <- Here
),
...