Last active
December 14, 2020 05:10
-
-
Save tcd93/4038412fce163ac9eb59a269cbf95faf to your computer and use it in GitHub Desktop.
Draggable widget fails on Web
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
final overlayCtnKey = GlobalKey(); | |
@override | |
Widget build(BuildContext context) { | |
final fab = FloatingActionButton( | |
onPressed: () {}); // works if switch to a widget without onTap/onPress... | |
return MaterialApp( | |
home: Stack( | |
children: [ | |
Container(key: overlayCtnKey), | |
DraggableWidget(containerKey: overlayCtnKey, child: fab), | |
], | |
), | |
); | |
} | |
} | |
class DraggableWidget extends StatefulWidget { | |
final Widget child; | |
final GlobalKey containerKey; | |
DraggableWidget({@required this.child, @required this.containerKey}); | |
@override | |
DraggableWidgetState createState() => DraggableWidgetState(); | |
} | |
class DraggableWidgetState extends State<DraggableWidget> { | |
double top, left; | |
@override | |
void initState() { | |
top = 50; | |
left = 50; | |
super.initState(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
final RenderBox backgroundRenderBox = widget.containerKey.currentContext.findRenderObject(); | |
return Positioned( | |
top: top, | |
left: left, | |
child: Draggable( | |
dragAnchor: DragAnchor.child, | |
feedback: widget.child, | |
child: widget.child, | |
childWhenDragging: const SizedBox(), | |
onDragEnd: (drag) { | |
final localOffset = backgroundRenderBox.globalToLocal(drag.offset); | |
setState(() { | |
top = localOffset.dy; | |
left = localOffset.dx; | |
}); | |
}, | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment