Skip to content

Instantly share code, notes, and snippets.

@osmanyz
Created February 23, 2024 22:34
Show Gist options
  • Select an option

  • Save osmanyz/28b86313820b839bfac41d6eb7cfa486 to your computer and use it in GitHub Desktop.

Select an option

Save osmanyz/28b86313820b839bfac41d6eb7cfa486 to your computer and use it in GitHub Desktop.
test drag and drop list flutter.dart
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({
super.key
});
@override
State<MyApp> createState() => _MyApp();
}
class _MyApp extends State<MyApp> {
final img1 = "https://static.nike.com/a/images/t_PDP_1728_v1/f_auto,q_auto:eco/a9b533c1-a480-4873-9ca8-2f75f5d8bd77/superfly-9-academy-mercurial-dream-speed-mg-y%C3%BCksek-bilekli-krampon-0nk3h4.png";
final img2 = "https://static.nike.com/a/images/t_PDP_1728_v1/f_auto,q_auto:eco/6ae11ec9-2160-4bde-be5b-ba845bdded11/force-1-low-easyon-ayakkab%C4%B1s%C4%B1-mC6SbX.png";
final img3 = "https://static.nike.com/a/images/t_PDP_1728_v1/f_auto,q_auto:eco/5d313213-ad9e-42f4-8fb9-464b9cd8b2f7/air-max-ishod-ayakkab%C4%B1s%C4%B1-8Gf0Px.png";
final List<dynamic> images = [];
@override
void initState() {
super.initState();
images.addAll([
{'image':img1, 'x': 0.0, 'y': 0.0},
{'image':img2, 'x': 0.0, 'y': 0.0},
{'image':img3, 'x': 0.0, 'y': 0.0}
]);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
themeMode: ThemeMode.dark,
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Stack(
children: List.generate(images.length, (index) {
final itm = images[index];
return DragDropWidget(
item: itm,
x: itm['x'],
y: itm['y'],
child: Image.network(itm['image'], width: 200, height: 200),
);
},
),
),
),
);
}
}
class DragDropWidget extends StatefulWidget {
final double? x;
final double? y;
final dynamic item;
final Widget child;
const DragDropWidget({
super.key,
this.x,
this.y,
this.item,
required this.child,
});
@override
State<DragDropWidget> createState() => _DragDropWidgetState();
}
class _DragDropWidgetState extends State<DragDropWidget> {
final GlobalKey _draggableKey = GlobalKey();
Offset _dragOffset = const Offset(0, 0);
@override
void initState() {
super.initState();
_dragOffset = Offset(widget.x!, widget.y!);
}
@override
Widget build(BuildContext context) {
return Positioned(
left: _dragOffset.dx,
top: _dragOffset.dy,
child: Draggable(
key: _draggableKey,
onDragEnd: (drag) {
RenderBox? renderBox = context.findRenderObject() as RenderBox;
onDragEnd(renderBox.globalToLocal(drag.offset));
// remove the item to the top
print(widget.item);
},
childWhenDragging: widget.child,
feedback: widget.child,
child: widget.child,
),
);
}
void onDragEnd(Offset offset) {
setState(() {
_dragOffset += offset;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment