Using NotificationListener with Custom Notification
You can create a custom notification system where the child sends its size up the widget tree:
dart
class SizeNotification extends Notification {
final Size size;
SizeNotification({required this.size});
}
class SizeNotifierWidget extends StatefulWidget {
final Widget child;
const SizeNotifierWidget({required this.child});
@override
_SizeNotifierWidgetState createState() => _SizeNotifierWidgetState();
}
class _SizeNotifierWidgetState extends State<SizeNotifierWidget> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
final RenderBox? renderBox =
context.findRenderObject() as RenderBox?;
if (renderBox != null) {
SizeNotification(size: renderBox.size).dispatch(context);
}
});
}
@override
Widget build(BuildContext context) => widget.child;
}
// In parent widget:
NotificationListener<SizeNotification>(
onNotification: (notification) {
print('Child size: ${notification.size}');
return true;
},
child: SizeNotifierWidget(
child: Container(child: Text('Child')),
),
)
Important Considerations
Timing: The child must be rendered before you can get its size. Use WidgetsBinding.instance.addPostFrameCallback to ensure the widget tree has been built.
Dynamic Sizes: If the child's size changes (e.g., due to content changes), you'll need to re-measure. Consider adding listeners or using the notification approach.
Performance: Avoid measuring sizes in the build method as it can cause infinite loops. Always measure after the frame has been rendered.
Layout Constraints: Remember that a child's size depends on the constraints given by its parent. If you need specific sizing behavior, consider using IntrinsicWidth/IntrinsicHeight widgets.
The GlobalKey approach is usually sufficient for most use cases, but choose the method that best fits your specific requirements.
User
The child widget should be snapped to a grid. Currently, the parent is a widget that is used to snap the child but the parent needs to know the size of the child to snap properly. I would prefer a separate snapping widget to be able to snap multiple different widgets to the grid. Suggest approaches how to go about this. I have considered merging the child and parent into one if the separate snapping widget is not feasible.
Assistant
Here are several approaches for creating a reusable grid snapping widget:
Approach 1: Self-Measuring Snapping Wrapper
Create a wrapper widget that measures its child and then repositions itself to snap to the grid:
The custom RenderObject approach provides the most control and best performance for grid snapping. Here's a comprehensive implementation:
Why Use a Custom RenderObject?
Performance: Direct control over layout and painting phases
Efficiency: No widget rebuilds for position changes
Flexibility: Complete control over hit testing, painting, and layout
Animation: Smooth animations without rebuilding widgets
Complete Implementation
dart
User
I have a Grid widget that contains a Stack, which is used to position the children. There is also a GridInfo object available, that contains cellSize and gridSize Size objects. My SnapToGrid widget uses a GestureDetector (which contains the child) inside a Positioned widget to snap. Assume there is a function snapGlobalToGrid that takes a global position from the GestureDetector and returns the snapped offset.
Which of these components can be reused here?
Assistant
Based on your existing structure, here are the components that can be reused and integrated:
1. Child Size Measurement Logic
Since you already have the positioning structure (Stack + Positioned + GestureDetector), you mainly need to add size measurement to your existing SnapToGrid widget:
dart
class SnapToGrid extends StatefulWidget {
final Widget child;
final GridInfo gridInfo;
final Offset initialPosition;
const SnapToGrid({
Key? key,
required this.child,
required this.gridInfo,
this.initialPosition = Offset.zero,
}) : super(key: key);
@override
_SnapToGridState createState() => _SnapToGridState();
}
class _SnapToGridState extends State<SnapToGrid> {
final GlobalKey _childKey = GlobalKey();
Size? _childSize;
late Offset _position;
@override
void initState() {
super.initState();
_position = widget.initialPosition;
WidgetsBinding.instance.addPostFrameCallback((_) {
_measureChild();
});
}
void _measureChild() {
final RenderBox? renderBox =
_childKey.currentContext?.findRenderObject() as RenderBox?;
if (renderBox != null) {
setState(() {
_childSize = renderBox.size;
// Re-snap with known size if needed
_position = _calculateSnappedPosition(_position);
});
}
}
Offset _calculateSnappedPosition(Offset globalPosition) {
// Use your existing snapGlobalToGrid function
final snapped = snapGlobalToGrid(globalPosition);
// Optionally adjust based on child size and snap strategy
if (_childSize != null) {
// e.g., for center snapping:
// return snapped - Offset(_childSize!.width / 2, _childSize!.height / 2);
}
return snapped;
}
@override
Widget build(BuildContext context) {
return Positioned(
left: _position.dx,
top: _position.dy,
child: GestureDetector(
onPanUpdate: (details) {
setState(() {
_position += details.delta;
});
},
onPanEnd: (_) {
setState(() {
_position = _calculateSnappedPosition(_position);
});
},
child: Container(
key: _childKey,
child: widget.child,
),
),
);
}
}
User
Provide an example on how my components would be integrated with the RenderObject method
Assistant
Here's how to integrate your existing components with a custom RenderObject approach:
1. Custom RenderObject that Works with Your Stack
dart
// Custom RenderObject that replaces Positioned but works within your Stack
class RenderGridPositioned extends RenderShiftedBox {
RenderGridPositioned({
required Offset position,
required GridInfo gridInfo,
required Function(Offset) snapGlobalToGrid,
RenderBox? child,
}) : _position = position,
_gridInfo = gridInfo,
_snapGlobalToGrid = snapGlobalToGrid,
super(child);
Offset _position;
Offset get position => _position;
set position(Offset value) {
if (_position != value) {
_position = value;
markNeedsLayout();
}
}
GridInfo _gridInfo;
GridInfo get gridInfo => _gridInfo;
set gridInfo(GridInfo value) {
if (_gridInfo != value) {
_gridInfo = value;
markNeedsLayout();
}
}
Function(Offset) _snapGlobalToGrid;
set snapGlobalToGrid(Function(Offset) value) {
_snapGlobalToGrid = value;
}
// Actual position (for dragging)
Offset _dragOffset = Offset.zero;
// Size of child for snapping calculations
Size? _childSize;
@override
void performLayout() {
if (child != null) {
// Layout child with incoming constraints
child!.layout(constraints.loosen(), parentUsesSize: true);
// Store child size for snapping calculations
_childSize = child!.size;
// Size is the same as the child
size = constraints.constrain(child!.size);
} else {
size = constraints.smallest;
}
}
@override
void paint(PaintingContext context, Offset offset) {
if (child != null) {
// Paint child at position + offset
final paintOffset = offset + _position + _dragOffset;
context.paintChild(child!, paintOffset);
}
}
// Expose method to update drag offset
void updateDragOffset(Offset delta) {
_dragOffset += delta;
markNeedsPaint();
}
// Snap to grid and reset drag offset
Offset snapToGrid() {
final currentGlobalPosition = _position + _dragOffset;
final snappedPosition = _snapGlobalToGrid(currentGlobalPosition);
_position = snappedPosition;
_dragOffset = Offset.zero;
markNeedsLayout();
return snappedPosition;
}
@override
bool hitTest(BoxHitTestResult result, {required Offset position}) {
if (child != null) {
final childOffset = _position + _dragOffset;
return result.addWithPaintOffset(
offset: childOffset,
position: position,
hitTest: (BoxHitTestResult result, Offset transformed) {
return child!.hitTest(result, position: transformed);
},
);
}
return false;
}
}
User
The grid gets a list of Item objects that each have a height and a widget property. The widget is built to match the height property. Inside the stack, each Item is mapped to a SnapToGrid that receives the Item's widget as a child.
Assistant
Given your architecture with Item objects, here's how to integrate the RenderObject approach:
1. Enhanced Item-Aware SnapToGrid
dart
class SnapToGrid extends StatefulWidget {
final Item item; // Pass the whole item instead of just the widget
final GridInfo gridInfo;
final Offset initialPosition;
final Function(Offset) snapGlobalToGrid;
final Function(Offset)? onSnapped;
const SnapToGrid({
Key? key,
required this.item,
required this.gridInfo,
required this.snapGlobalToGrid,
this.initialPosition = Offset.zero,
this.onSnapped,
}) : super(key: key);
@override
_SnapToGridState createState() => _SnapToGridState();
}
class _SnapToGridState extends State<SnapToGrid> {
late Offset _position;
final GlobalKey _renderKey = GlobalKey();
Size? _measuredSize;
@override
void initState() {
super.initState();
_position = widget.initialPosition;
// Since we know the height, we can estimate initial size
// This helps with immediate snapping before measurement
_estimateInitialSize();
}
void _estimateInitialSize() {
// Use the item's height property for immediate calculations
WidgetsBinding.instance.addPostFrameCallback((_) {
_measureActualSize();
});
}
void _measureActualSize() {
final renderObject = _renderKey.currentContext?.findRenderObject() as RenderBox?;
if (renderObject != null && renderObject.hasSize) {
setState(() {
_measuredSize = renderObject.size;
// Verify the measured height matches the item height
assert(
(_measuredSize!.height - widget.item.height).abs() < 1.0,
'Item widget height does not match item.height property'
);
});
}
}
@override
Widget build(BuildContext context) {
return GridPositioned(
key: _renderKey,
position: _position,
gridInfo: widget.gridInfo,
snapGlobalToGrid: widget.snapGlobalToGrid,
itemHeight: widget.item.height, // Pass item height to RenderObject
child: GestureDetector(
onPanUpdate: (details) {
final renderObject = _renderKey.currentContext?.findRenderObject()
as RenderGridPositioned?;
renderObject?.updateDragOffset(details.delta);
},
onPanEnd: (_) {
final renderObject = _renderKey.currentContext?.findRenderObject()
as RenderGridPositioned?;
if (renderObject != null) {
final snappedPosition = renderObject.snapToGrid();
setState(() {
_position = snappedPosition;
});
widget.onSnapped?.call(snappedPosition);
}
},
child: widget.item.widget, // Use the pre-built widget from Item
),
);
}
}
User
Explain again how SnapToGrid would be constructed and how it would actually snap its child.
Assistant
Let me explain the SnapToGrid construction and snapping mechanism step by step:
1. Construction Flow
dart
// In your Grid widget, items are mapped to SnapToGrid widgets:
Stack(
children: items.map((item) {
return SnapToGrid(
item: item, // Pass the entire Item object
gridInfo: gridInfo, // Grid configuration
snapGlobalToGrid: snapFunction, // Your snapping function
initialPosition: Offset(0, 0), // Starting position
child: item.widget, // The pre-built widget from Item
);
}).toList(),
)
2. How SnapToGrid Actually Works
Here's a detailed breakdown of the snapping mechanism:
dart
User
I forgot that snapGlobalToGrid also requires the size of the child as well as the gridInfo
Assistant
Ah, that's an important detail! Let me update the implementation to properly pass the child size to your snapGlobalToGrid function:
1. Updated SnapToGrid with Size-Aware Snapping
dart
class SnapToGrid extends StatefulWidget {
final Widget child;
final GridInfo gridInfo;
final Function(Offset, Size, GridInfo) snapGlobalToGrid; // Updated signature
final Offset initialPosition;
final Function(Offset)? onSnapped;
const SnapToGrid({
Key? key,
required this.child,
required this.gridInfo,
required this.snapGlobalToGrid,
this.initialPosition = Offset.zero,
this.onSnapped,
}) : super(key: key);
@override
_SnapToGridState createState() => _SnapToGridState();
}
class _SnapToGridState extends State<SnapToGrid> {
late Offset _position;
Offset _dragOffset = Offset.zero;
final GlobalKey _childKey = GlobalKey();
Size? _childSize;
// Flag to track if we need to snap after measuring
bool _snapAfterMeasure = false;
@override
void initState() {
super.initState();
_position = widget.initialPosition;
// Measure child and potentially snap initial position
WidgetsBinding.instance.addPostFrameCallback((_) {
_measureAndSnapInitial();
});
}
void _measureAndSnapInitial() {
final RenderBox? renderBox =
_childKey.currentContext?.findRenderObject() as RenderBox?;
if (renderBox != null && renderBox.hasSize) {
setState(() {
_childSize = renderBox.size;
// Now that we have the size, snap the initial position
if (_childSize != null) {
_position = widget.snapGlobalToGrid(
_position,
_childSize!,
widget.gridInfo,
);
}
});
}
}
@override
Widget build(BuildContext context) {
final currentPosition = _position + _dragOffset;
return Positioned(
left: currentPosition.dx,
top: currentPosition.dy,
child: GestureDetector(
onPanStart: (details) {
setState(() {
_dragOffset = Offset.zero;
});
},
onPanUpdate: (details) {
setState(() {
_dragOffset += details.delta;
});
},
onPanEnd: (details) {
_performSnap();
},
child: Container(
key: _childKey,
child: widget.child,
),
),
);
}
void _performSnap() {
// Can't snap without child size
if (_childSize == null) {
// Schedule snap after measurement
_snapAfterMeasure = true;
return;
}
final currentGlobalPosition = _position + _dragOffset;
// Call snap function with all required parameters
final snappedPosition = widget.snapGlobalToGrid(
currentGlobalPosition,
_childSize!,
widget.gridInfo,
);
setState(() {
_position = snappedPosition;
_dragOffset = Offset.zero;
});
widget.onSnapped?.call(snappedPosition);
}
}
User
Is it possible to integrate the GestureDetector into SnapToGrid or RenderSnapToGrid?
Assistant
Yes! Integrating the GestureDetector into SnapToGrid makes the API cleaner and ensures gesture handling is always part of the snapping behavior. Here are both approaches:
I want to recalculate the position of the child item in onPanUpdate. So far, I used a position property in the SnapToGrid widget and setState. As now SnapToGrid is not a widget anymore, how do I do this?
Assistant
You're right - with a RenderObject approach, you can't use setState. Here are the solutions:
1. Pure RenderObject Approach - Internal Position Updates
The RenderObject manages position internally and calls markNeedsPaint() to trigger repaints:
dart
User
Now integrate the GestureDetector into SnapToGrid
Assistant
Here's a complete implementation of SnapToGrid with integrated GestureDetector:
dart
User
The snapping code in onPanUpdate and onPanStart is the same for all children. I would like it hidden in SnapToGrid. Is this possible?
Assistant
Yes, absolutely! You can encapsulate all the common snapping logic inside SnapToGrid. Here's how:
dart
User
Your last approach does not use a RenderObject anymore. Isn't this worse performance wise? Is this possible using a RenderObject?
Assistant
You're absolutely right! The RenderObject approach is more performant, especially for dragging operations. Here's how to encapsulate all the snapping logic in a RenderObject:
dart
User
Okay, let's use the LayoutBuilder method. Here is some pseudo code to for API design:
build() {
return SnapToGrid(
gridInfo: gridInfo,
onTap: () {...}, // Not defined inside SnapToGrid, but ItemAWidget should have a tap action
child: Container(
width: width,
height: height,
color: color,
),
)
}
Assistant
Based on your API design, here's a complete implementation:
dart
User
SnapToGrid should receive an Item object, that contains the height. Also, it should contain a GestureDetector that will handle the snapping in it's onPanUpdate. Remember, that snapping requires the size of the child.
Assistant
Here's the updated implementation with SnapToGrid receiving an Item object and handling snapping in onPanUpdate:
Create a more flexible system with different snapping strategies:
dart
abstract class SnapStrategy {
Offset snap(Offset position, Size size, double gridSize);
}
class TopLeftSnapStrategy implements SnapStrategy {
@override
Offset snap(Offset position, Size size, double gridSize) {
return Offset(
(position.dx / gridSize).round() * gridSize,
(position.dy / gridSize).round() * gridSize,
);
}
}
class CenterSnapStrategy implements SnapStrategy {
@override
Offset snap(Offset position, Size size, double gridSize) {
final center = position + Offset(size.width / 2, size.height / 2);
final snappedCenter = Offset(
(center.dx / gridSize).round() * gridSize,
(center.dy / gridSize).round() * gridSize,
);
return snappedCenter - Offset(size.width / 2, size.height / 2);
}
}
class GridSnap extends StatelessWidget {
final Widget child;
final double gridSize;
final SnapStrategy strategy;
final bool showGrid;
const GridSnap({
Key? key,
required this.child,
this.gridSize = 20.0,
this.strategy = const TopLeftSnapStrategy(),
this.showGrid = false,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Stack(
children: [
if (showGrid) GridOverlay(gridSize: gridSize),
MeasureSize(
onChange: (size) {
// Size is available here for any additional logic
},
child: child,
),
],
);
}
}
class MeasureSize extends StatefulWidget {
final Widget child;
final Function(Size) onChange;
const MeasureSize({
Key? key,
required this.onChange,
required this.child,
}) : super(key: key);
@override
_MeasureSizeState createState() => _MeasureSizeState();
}
class _MeasureSizeState extends State<MeasureSize> {
@override
Widget build(BuildContext context) {
SchedulerBinding.instance.addPostFrameCallback(postFrameCallback);
return Container(
key: widgetKey,
child: widget.child,
);
}
var widgetKey = GlobalKey();
var oldSize;
void postFrameCallback(_) {
var context = widgetKey.currentContext;
if (context == null) return;
var newSize = context.size;
if (oldSize == newSize) return;
oldSize = newSize;
widget.onChange(newSize!);
}
}
Recommendation
For your use case, I recommend Approach 1 or 2:
Approach 1 is simpler and self-contained, good for basic grid snapping
Approach 2 with the controller pattern is better if you need:
Coordination between multiple snapped widgets
Different snapping strategies
State management integration
Animation support
Both approaches keep the snapping logic separate from your child widgets, making them reusable. The controller approach also makes it easier to add features like:
Snap-to-widget (widgets snapping to each other)
Grid visualization
Undo/redo functionality
Saving/loading positions
Would you like me to elaborate on any of these approaches or help you implement a specific feature?
// The core RenderObject that handles grid snapping
class RenderGridSnap extends RenderProxyBox {
RenderGridSnap({
required double gridSize,
required Offset position,
required SnapAlignment snapAlignment,
required bool animateSnap,
RenderBox? child,
}) : _gridSize = gridSize,
_position = position,
_snapAlignment = snapAlignment,
_animateSnap = animateSnap,
super(child);
double _gridSize;
double get gridSize => _gridSize;
set gridSize(double value) {
if (_gridSize != value) {
_gridSize = value;
_updateSnappedPosition();
markNeedsPaint();
}
}
Offset _position;
Offset get position => _position;
set position(Offset value) {
if (_position != value) {
_position = value;
_updateSnappedPosition();
markNeedsPaint();
}
}
SnapAlignment _snapAlignment;
SnapAlignment get snapAlignment => _snapAlignment;
set snapAlignment(SnapAlignment value) {
if (_snapAlignment != value) {
_snapAlignment = value;
_updateSnappedPosition();
markNeedsPaint();
}
}
bool _animateSnap;
bool get animateSnap => _animateSnap;
set animateSnap(bool value) {
if (_animateSnap != value) {
_animateSnap = value;
}
}
// Actual position after snapping
Offset _snappedPosition = Offset.zero;
// For smooth animation
Offset _animatedPosition = Offset.zero;
AnimationController? _animationController;
@override
void attach(PipelineOwner owner) {
super.attach(owner);
if (_animateSnap) {
_setupAnimation();
}
}
@override
void detach() {
_animationController?.dispose();
super.detach();
}
void _setupAnimation() {
_animationController = AnimationController(
duration: const Duration(milliseconds: 150),
vsync: SchedulerBinding.instance,
);
_animationController!.addListener(() {
markNeedsPaint();
});
}
void _updateSnappedPosition() {
if (child == null) return;
final childSize = child!.size;
final snappedPos = _calculateSnappedPosition(_position, childSize);
if (_animateSnap && _animationController != null) {
// Animate to new position
final animation = Tween<Offset>(
begin: _animatedPosition,
end: snappedPos,
).animate(CurvedAnimation(
parent: _animationController!,
curve: Curves.easeInOut,
));
_animationController!.forward(from: 0).then((_) {
_animatedPosition = snappedPos;
});
_snappedPosition = snappedPos;
} else {
_snappedPosition = snappedPos;
_animatedPosition = snappedPos;
}
}
Offset _calculateSnappedPosition(Offset position, Size childSize) {
switch (_snapAlignment) {
case SnapAlignment.topLeft:
return _snapPoint(position);
case SnapAlignment.center:
final center = position + Offset(childSize.width / 2, childSize.height / 2);
final snappedCenter = _snapPoint(center);
return snappedCenter - Offset(childSize.width / 2, childSize.height / 2);
case SnapAlignment.topRight:
final topRight = position + Offset(childSize.width, 0);
final snappedTopRight = _snapPoint(topRight);
return snappedTopRight - Offset(childSize.width, 0);
case SnapAlignment.bottomLeft:
final bottomLeft = position + Offset(0, childSize.height);
final snappedBottomLeft = _snapPoint(bottomLeft);
return snappedBottomLeft - Offset(0, childSize.height);
case SnapAlignment.bottomRight:
final bottomRight = position + Offset(childSize.width, childSize.height);
final snappedBottomRight = _snapPoint(bottomRight);
return snappedBottomRight - Offset(childSize.width, childSize.height);
}
}
Offset _snapPoint(Offset point) {
return Offset(
(point.dx / _gridSize).round() * _gridSize,
(point.dy / _gridSize).round() * _gridSize,
);
}
@override
void performLayout() {
if (child != null) {
child!.layout(constraints, parentUsesSize: true);
size = constraints.constrain(child!.size);
_updateSnappedPosition();
} else {
size = constraints.smallest;
}
}
@override
void paint(PaintingContext context, Offset offset) {
if (child != null) {
final paintOffset = _animateSnap && _animationController != null
? offset + Tween<Offset>(
begin: _animatedPosition,
end: _snappedPosition,
).evaluate(_animationController!)
: offset + _snappedPosition;
context.paintChild(child!, paintOffset);
// Optional: Paint debug info
if (debugPaintSizeEnabled) {
_paintDebugInfo(context, offset);
}
}
}
void _paintDebugInfo(PaintingContext context, Offset offset) {
final paint = Paint()
..color = Colors.red.withOpacity(0.5)
..style = PaintingStyle.stroke
..strokeWidth = 2;
// Draw grid lines
final canvas = context.canvas;
final bounds = offset & size;
for (double x = bounds.left; x <= bounds.right; x += _gridSize) {
canvas.drawLine(
Offset(x, bounds.top),
Offset(x, bounds.bottom),
paint..color = Colors.grey.withOpacity(0.2),
);
}
for (double y = bounds.top; y <= bounds.bottom; y += _gridSize) {
canvas.drawLine(
Offset(bounds.left, y),
Offset(bounds.right, y),
paint..color = Colors.grey.withOpacity(0.2),
);
}
// Draw snap point
final snapPoint = offset + _snappedPosition;
canvas.drawCircle(snapPoint, 5, paint..color = Colors.red);
}
@override
bool hitTestChildren(BoxHitTestResult result, {required Offset position}) {
if (child != null) {
final childOffset = _animateSnap && _animationController != null
? Tween<Offset>(
begin: _animatedPosition,
end: _snappedPosition,
).evaluate(_animationController!)
: _snappedPosition;
return result.addWithPaintOffset(
offset: childOffset,
position: position,
hitTest: (BoxHitTestResult result, Offset transformed) {
return child!.hitTest(result, position: transformed);
},
);
}
return false;
}
}
// Widget that uses the custom RenderObject
class GridSnapWidget extends SingleChildRenderObjectWidget {
final double gridSize;
final Offset position;
final SnapAlignment snapAlignment;
final bool animateSnap;
final ValueChanged<Offset>? onPositionChanged;
const GridSnapWidget({
Key? key,
required Widget child,
this.gridSize = 20.0,
this.position = Offset.zero,
this.snapAlignment = SnapAlignment.topLeft,
this.animateSnap = true,
this.onPositionChanged,
}) : super(key: key, child: child);
@override
RenderGridSnap createRenderObject(BuildContext context) {
return RenderGridSnap(
gridSize: gridSize,
position: position,
snapAlignment: snapAlignment,
animateSnap: animateSnap,
);
}
@override
void updateRenderObject(BuildContext context, RenderGridSnap renderObject) {
renderObject
..gridSize = gridSize
..position = position
..snapAlignment = snapAlignment
..animateSnap = animateSnap;
}
}
enum SnapAlignment {
topLeft,
center,
topRight,
bottomLeft,
bottomRight,
}
// Draggable wrapper that works with the grid snap
class DraggableGridSnap extends StatefulWidget {
final Widget child;
final double gridSize;
final Offset initialPosition;
final SnapAlignment snapAlignment;
final bool showFeedback;
final ValueChanged<Offset>? onSnapped;
const DraggableGridSnap({
Key? key,
required this.child,
this.gridSize = 20.0,
this.initialPosition = Offset.zero,
this.snapAlignment = SnapAlignment.topLeft,
this.showFeedback = true,
this.onSnapped,
}) : super(key: key);
@override
_DraggableGridSnapState createState() => _DraggableGridSnapState();
}
class _DraggableGridSnapState extends State<DraggableGridSnap> {
late Offset _position;
Offset _dragOffset = Offset.zero;
bool _isDragging = false;
@override
void initState() {
super.initState();
_position = widget.initialPosition;
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
Positioned(
left: 0,
top: 0,
child: GestureDetector(
onPanStart: (_) {
setState(() {
_isDragging = true;
_dragOffset = Offset.zero;
});
},
onPanUpdate: (details) {
setState(() {
_dragOffset = details.localPosition - details.delta;
_position += details.delta;
});
},
onPanEnd: (_) {
setState(() {
_isDragging = false;
widget.onSnapped?.call(_position);
});
},
child: GridSnapWidget(
gridSize: widget.gridSize,
position: _position,
snapAlignment: widget.snapAlignment,
animateSnap: !_isDragging,
child: AnimatedOpacity(
duration: const Duration(milliseconds: 150),
opacity: _isDragging ? 0.7 : 1.0,
child: widget.child,
),
),
),
),
if (_isDragging && widget.showFeedback)
Positioned(
left: _position.dx,
top: _position.dy - 30,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Colors.black87,
borderRadius: BorderRadius.circular(4),
),
child: Text(
'x: ${_position.dx.round()}, y: ${_position.dy.round()}',
style: const TextStyle(color: Colors.white, fontSize: 12),
),
),
),
],
);
}
}
// Advanced grid container that manages multiple snapped widgets
class GridSnapContainer extends StatelessWidget {
final List<Widget> children;
final double gridSize;
final bool showGrid;
final Color gridColor;
const GridSnapContainer({
Key? key,
required this.children,
this.gridSize = 20.0,
this.showGrid = true,
this.gridColor = Colors.grey,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Stack(
children: [
if (showGrid)
CustomPaint(
size: Size.infinite,
painter: GridPainter(
gridSize: gridSize,
color: gridColor.withOpacity(0.2),
),
),
...children,
],
);
}
}
class GridPainter extends CustomPainter {
final double gridSize;
final Color color;
GridPainter({required this.gridSize, required this.color});
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = color
..strokeWidth = 0.5;
for (double x = 0; x <= size.width; x += gridSize) {
canvas.drawLine(Offset(x, 0), Offset(x, size.height), paint);
}
for (double y = 0; y <= size.height; y += gridSize) {
canvas.drawLine(Offset(0, y), Offset(size.width, y), paint);
}
}
@override
bool shouldRepaint(GridPainter oldDelegate) {
return oldDelegate.gridSize != gridSize || oldDelegate.color != color;
}
}
Performance: No widget rebuilds during drag operations
Smooth Animations: Direct control over paint phase enables smooth transitions
Hit Testing: Precise control over touch detection
Memory Efficient: Fewer widget allocations
Custom Paint Effects: Easy to add visual feedback like shadows, highlights
Advanced Features You Can Add
Magnetic Snapping: Snap to other widgets when close
Rotation Snapping: Snap rotation angles to increments
Constrained Movement: Limit movement to specific axes
Multi-Select: Select and move multiple widgets together
Zoom/Pan Support: Work with transformable containers
This approach is ideal when you need maximum performance and control, especially for applications like design tools, diagram editors, or games where many objects need to snap to a grid smoothly.
Optimization: Easy to implement viewport culling for large grids
This approach leverages your Item structure while providing the performance benefits of custom RenderObjects.
class SnapToGrid extends StatefulWidget {
final Widget child; // The Item's widget
final GridInfo gridInfo;
final Function(Offset) snapGlobalToGrid;
final Offset initialPosition;
const SnapToGrid({
Key? key,
required this.child,
required this.gridInfo,
required this.snapGlobalToGrid,
this.initialPosition = Offset.zero,
}) : super(key: key);
@override
_SnapToGridState createState() => _SnapToGridState();
}
class _SnapToGridState extends State<SnapToGrid> {
// Current position of the widget
late Offset _position;
// Temporary offset while dragging (not snapped)
Offset _dragOffset = Offset.zero;
// Key to measure child size
final GlobalKey _childKey = GlobalKey();
Size? _childSize;
@override
void initState() {
super.initState();
_position = widget.initialPosition;
// Measure child after first frame
WidgetsBinding.instance.addPostFrameCallback((_) {
_measureChild();
});
}
void _measureChild() {
final RenderBox? renderBox =
_childKey.currentContext?.findRenderObject() as RenderBox?;
if (renderBox != null && renderBox.hasSize) {
setState(() {
_childSize = renderBox.size;
});
}
}
@override
Widget build(BuildContext context) {
// The actual position is _position + _dragOffset
final currentPosition = _position + _dragOffset;
return Positioned(
left: currentPosition.dx,
top: currentPosition.dy,
child: GestureDetector(
onPanStart: (details) {
// Reset drag offset when starting a new drag
setState(() {
_dragOffset = Offset.zero;
});
},
onPanUpdate: (details) {
// While dragging, only update the temporary offset
// This gives smooth dragging without snapping
setState(() {
_dragOffset += details.delta;
});
},
onPanEnd: (details) {
// When drag ends, calculate the snapped position
_performSnap();
},
child: Container(
key: _childKey,
child: widget.child, // The Item's widget
),
),
);
}
void _performSnap() {
// Current position in global coordinates
final currentGlobalPosition = _position + _dragOffset;
// Call your snap function to get snapped position
final snappedPosition = widget.snapGlobalToGrid(currentGlobalPosition);
setState(() {
// Update the base position to the snapped position
_position = snappedPosition;
// Reset drag offset since we've snapped
_dragOffset = Offset.zero;
});
}
}
3. The Snapping Process Visualized
dart
// Example of what happens during drag and snap:
// 1. Initial state
_position = Offset(50, 50); // Snapped position
_dragOffset = Offset.zero; // No drag
// Widget is at (50, 50)
// 2. User starts dragging
onPanUpdate: delta = Offset(15, 7)
_position = Offset(50, 50); // Unchanged
_dragOffset = Offset(15, 7); // Accumulates drag
// Widget is at (65, 57) - smooth dragging
// 3. User continues dragging
onPanUpdate: delta = Offset(8, 3)
_position = Offset(50, 50); // Still unchanged
_dragOffset = Offset(23, 10); // Accumulates
// Widget is at (73, 60)
// 4. User releases (onPanEnd)
currentGlobalPosition = Offset(50, 50) + Offset(23, 10) = Offset(73, 60);
// Your snapGlobalToGrid function is called
snappedPosition = snapGlobalToGrid(Offset(73, 60));
// If grid size is 25x25, this returns Offset(75, 50)
// 5. Final state after snap
_position = Offset(75, 50); // New snapped position
_dragOffset = Offset.zero; // Reset
// Widget jumps to (75, 50)
4. Integration with Your Components
dart
class Grid extends StatelessWidget {
final GridInfo gridInfo;
final List<Item> items;
// Your existing snap function
Offset snapGlobalToGrid(Offset globalPosition) {
final cellWidth = gridInfo.cellSize.width;
final cellHeight = gridInfo.cellSize.height;
return Offset(
(globalPosition.dx / cellWidth).round() * cellWidth,
(globalPosition.dy / cellHeight).round() * cellHeight,
);
}
@override
Widget build(BuildContext context) {
return Stack(
children: items.map((item) {
return SnapToGrid(
key: ValueKey(item.id),
child: item.widget, // Pre-built widget with correct height
gridInfo: gridInfo,
snapGlobalToGrid: snapGlobalToGrid,
initialPosition: Offset(0, 0),
);
}).toList(),
);
}
}
5. With Animation for Smooth Snapping
dart
void _performSnap() {
final currentGlobalPosition = _position + _dragOffset;
final snappedPosition = widget.snapGlobalToGrid(currentGlobalPosition);
// Animate from current position to snapped position
_animationController.forward(from: 0);
_positionAnimation = Tween<Offset>(
begin: currentGlobalPosition,
end: snappedPosition,
).animate(CurvedAnimation(
parent: _animationController,
curve: Curves.easeOutCubic,
));
_animationController.addStatusListener((status) {
if (status == AnimationStatus.completed) {
setState(() {
_position = snappedPosition;
_dragOffset = Offset.zero;
});
}
});
}
Key Points
Two-Phase Position:
_position: The last snapped position
_dragOffset: Temporary offset during drag
Actual position = _position + _dragOffset
Smooth Dragging: During drag, only _dragOffset changes, giving smooth movement
Snap on Release: When drag ends, calculate new snapped position and reset
Child Measurement: The child size is measured after first build for accurate snapping
Your Components: Your snapGlobalToGrid function and GridInfo are used as-is
This approach keeps the snapping logic separate and reusable while integrating cleanly with your existing Item/Grid structure.
2. Grid Widget with Proper Snap Function
dart
class Grid extends StatelessWidget {
final GridInfo gridInfo;
final List<Item> items;
final Map<Item, Offset> initialPositions;
const Grid({
Key? key,
required this.gridInfo,
required this.items,
this.initialPositions = const {},
}) : super(key: key);
// Your snap function that uses size and gridInfo
Offset snapGlobalToGrid(Offset globalPosition, Size childSize, GridInfo gridInfo) {
final cellWidth = gridInfo.cellSize.width;
final cellHeight = gridInfo.cellSize.height;
// Example: Snap based on center of widget
final center = globalPosition + Offset(childSize.width / 2, childSize.height / 2);
final snappedCenter = Offset(
(center.dx / cellWidth).round() * cellWidth,
(center.dy / cellHeight).round() * cellHeight,
);
// Return top-left position after centering
return snappedCenter - Offset(childSize.width / 2, childSize.height / 2);
// Or snap based on top-left corner
// return Offset(
// (globalPosition.dx / cellWidth).round() * cellWidth,
// (globalPosition.dy / cellHeight).round() * cellHeight,
// );
}
@override
Widget build(BuildContext context) {
return Stack(
children: items.map((item) {
return SnapToGrid(
key: ValueKey(item.id),
child: item.widget,
gridInfo: gridInfo,
snapGlobalToGrid: snapGlobalToGrid,
initialPosition: initialPositions[item] ?? Offset.zero,
onSnapped: (position) {
// Update position storage if needed
},
);
}).toList(),
);
}
}
3. With RenderObject Approach
dart
class RenderGridPositioned extends RenderShiftedBox {
RenderGridPositioned({
required Offset position,
required GridInfo gridInfo,
required Function(Offset, Size, GridInfo) snapGlobalToGrid,
RenderBox? child,
}) : _position = position,
_gridInfo = gridInfo,
_snapGlobalToGrid = snapGlobalToGrid,
super(child);
Offset _position;
GridInfo _gridInfo;
Function(Offset, Size, GridInfo) _snapGlobalToGrid;
Offset _dragOffset = Offset.zero;
Size? _childSize;
@override
void performLayout() {
if (child != null) {
child!.layout(constraints.loosen(), parentUsesSize: true);
_childSize = child!.size;
size = constraints.constrain(child!.size);
// Can snap initial position now that we have size
if (_childSize != null) {
_position = _snapGlobalToGrid(_position, _childSize!, _gridInfo);
}
} else {
size = constraints.smallest;
}
}
Offset snapToGrid() {
if (_childSize == null) {
// Can't snap without size
return _position;
}
final currentGlobalPosition = _position + _dragOffset;
final snappedPosition = _snapGlobalToGrid(
currentGlobalPosition,
_childSize!,
_gridInfo,
);
_position = snappedPosition;
_dragOffset = Offset.zero;
markNeedsLayout();
return snappedPosition;
}
// ... rest of implementation
}
4. Alternative: Item-Based Approach with Known Heights
Since your Items have a height property, you could optimize by using that for immediate snapping:
dart
class SnapToGrid extends StatefulWidget {
final Item item; // Pass item to access height
final GridInfo gridInfo;
final Function(Offset, Size, GridInfo) snapGlobalToGrid;
final Offset initialPosition;
const SnapToGrid({
Key? key,
required this.item,
required this.gridInfo,
required this.snapGlobalToGrid,
this.initialPosition = Offset.zero,
}) : super(key: key);
@override
_SnapToGridState createState() => _SnapToGridState();
}
class _SnapToGridState extends State<SnapToGrid> {
late Offset _position;
Offset _dragOffset = Offset.zero;
final GlobalKey _childKey = GlobalKey();
Size? _measuredSize;
@override
void initState() {
super.initState();
// Use item height for immediate approximate snapping
final estimatedSize = Size(100, widget.item.height); // Estimate width
_position = widget.snapGlobalToGrid(
widget.initialPosition,
estimatedSize,
widget.gridInfo,
);
// Get actual size after render
WidgetsBinding.instance.addPostFrameCallback((_) {
_measureAndUpdateSnap();
});
}
void _measureAndUpdateSnap() {
final RenderBox? renderBox =
_childKey.currentContext?.findRenderObject() as RenderBox?;
if (renderBox != null && renderBox.hasSize) {
final actualSize = renderBox.size;
// Re-snap with actual size if different from estimate
if (_measuredSize != actualSize) {
setState(() {
_measuredSize = actualSize;
_position = widget.snapGlobalToGrid(
_position,
actualSize,
widget.gridInfo,
);
});
}
}
}
void _performSnap() {
// Use measured size if available, otherwise use height from item
final size = _measuredSize ?? Size(100, widget.item.height);
final currentGlobalPosition = _position + _dragOffset;
final snappedPosition = widget.snapGlobalToGrid(
currentGlobalPosition,
size,
widget.gridInfo,
);
setState(() {
_position = snappedPosition;
_dragOffset = Offset.zero;
});
}
@override
Widget build(BuildContext context) {
return Positioned(
left: (_position + _dragOffset).dx,
top: (_position + _dragOffset).dy,
child: GestureDetector(
onPanUpdate: (details) {
setState(() {
_dragOffset += details.delta;
});
},
onPanEnd: (_) => _performSnap(),
child: Container(
key: _childKey,
child: widget.item.widget,
),
),
);
}
}
Key Changes
Snap Function Signature: Now takes (Offset, Size, GridInfo)
Deferred Snapping: Can't snap until child size is measured
Initial Position: May need adjustment after size is known
Item Height Usage: Can use item.height for immediate approximate snapping
This ensures your snapGlobalToGrid function always has the size information it needs to properly calculate grid snapping based on the widget's dimensions.
2. RenderObject Approach: Direct Gesture Handling
This approach implements gesture detection directly in the RenderObject:
dart
class RenderSnapToGrid extends RenderProxyBox {
RenderSnapToGrid({
required Offset position,
required GridInfo gridInfo,
required Function(Offset, Size, GridInfo) snapGlobalToGrid,
required bool enableDragging,
required VoidCallback onNeedsPaint,
RenderBox? child,
}) : _position = position,
_gridInfo = gridInfo,
_snapGlobalToGrid = snapGlobalToGrid,
_enableDragging = enableDragging,
_onNeedsPaint = onNeedsPaint,
super(child);
Offset _position;
final GridInfo _gridInfo;
final Function(Offset, Size, GridInfo) _snapGlobalToGrid;
final bool _enableDragging;
final VoidCallback _onNeedsPaint;
// Drag state
Offset _dragOffset = Offset.zero;
bool _isDragging = false;
Offset? _lastPointerPosition;
set position(Offset value) {
if (_position != value) {
_position = value;
markNeedsPaint();
}
}
@override
bool hitTest(BoxHitTestResult result, {required Offset position}) {
if (!_enableDragging) {
return super.hitTest(result, position: position);
}
// Always hit test children first
final bool hitTarget = super.hitTest(result, position: position);
// Add ourselves to handle drag gestures
if (size.contains(position)) {
result.add(BoxHitTestEntry(this, position));
return true;
}
return hitTarget;
}
@override
void handleEvent(PointerEvent event, covariant BoxHitTestEntry entry) {
if (!_enableDragging) return;
if (event is PointerDownEvent) {
_isDragging = true;
_lastPointerPosition = event.localPosition;
} else if (event is PointerMoveEvent && _isDragging) {
if (_lastPointerPosition != null) {
final delta = event.localPosition - _lastPointerPosition!;
_dragOffset += delta;
_lastPointerPosition = event.localPosition;
markNeedsPaint();
_onNeedsPaint();
}
} else if (event is PointerUpEvent && _isDragging) {
_performSnap();
_isDragging = false;
_lastPointerPosition = null;
}
}
void _performSnap() {
if (child == null || !child!.hasSize) return;
final currentPosition = _position + _dragOffset;
final snappedPosition = _snapGlobalToGrid(
currentPosition,
child!.size,
_gridInfo,
);
_position = snappedPosition;
_dragOffset = Offset.zero;
markNeedsPaint();
_onNeedsPaint();
}
@override
void paint(PaintingContext context, Offset offset) {
if (child != null) {
final paintOffset = offset + _position + _dragOffset;
context.paintChild(child!, paintOffset);
// Optional: Paint drag indicator
if (_isDragging && debugPaintSizeEnabled) {
final paint = Paint()
..color = Colors.blue.withOpacity(0.3)
..style = PaintingStyle.stroke
..strokeWidth = 2;
context.canvas.drawRect(
paintOffset & child!.size,
paint,
);
}
}
}
}
class SnapToGrid extends SingleChildRenderObjectWidget {
final Offset position;
final GridInfo gridInfo;
final Function(Offset, Size, GridInfo) snapGlobalToGrid;
final bool enableDragging;
final Function(Offset)? onSnapped;
const SnapToGrid({
Key? key,
required Widget child,
required this.position,
required this.gridInfo,
required this.snapGlobalToGrid,
this.enableDragging = true,
this.onSnapped,
}) : super(key: key, child: child);
@override
RenderSnapToGrid createRenderObject(BuildContext context) {
return RenderSnapToGrid(
position: position,
gridInfo: gridInfo,
snapGlobalToGrid: snapGlobalToGrid,
enableDragging: enableDragging,
onNeedsPaint: () {
// Trigger rebuild if needed for state updates
(context as Element).markNeedsBuild();
},
);
}
@override
void updateRenderObject(BuildContext context, RenderSnapToGrid renderObject) {
renderObject.position = position;
}
}
No Widget Rebuilds: Position updates only trigger repaints, not rebuilds
Direct Hit Testing: More efficient gesture detection
Optimized Painting: Can use painting optimizations like layers
Less Memory Allocation: No new widget instances during drag
Alternative: Hybrid Approach for Best of Both Worlds
dart
class SnapToGrid extends StatefulWidget {
final Widget child;
final GridInfo gridInfo;
final Function(Offset, Size, GridInfo) snapGlobalToGrid;
final Offset initialPosition;
final Function(Offset)? onSnapped;
const SnapToGrid({
Key? key,
required this.child,
required this.gridInfo,
required this.snapGlobalToGrid,
this.initialPosition = Offset.zero,
this.onSnapped,
}) : super(key: key);
@override
_SnapToGridState createState() => _SnapToGridState();
}
class _SnapToGridState extends State<SnapToGrid> {
late Offset _position;
@override
void initState() {
super.initState();
_position = widget.initialPosition;
}
void _handleSnap(Offset newPosition) {
setState(() {
_position = newPosition;
});
widget.onSnapped?.call(newPosition);
}
@override
Widget build(BuildContext context) {
return Positioned(
left: _position.dx,
top: _position.dy,
child: _InternalSnapRenderObject(
gridInfo: widget.gridInfo,
snapGlobalToGrid: widget.snapGlobalToGrid,
onSnapped: _handleSnap,
child: widget.child,
),
);
}
}
// The RenderObject handles dragging without rebuilds
class _InternalSnapRenderObject extends SingleChildRenderObjectWidget {
// ... implementation similar to above but simpler
}
The pure RenderObject approach gives you the best performance, especially when dragging multiple items simultaneously. The gesture handling and position updates happen entirely in the render layer without triggering any widget rebuilds.
Separation of Concerns: SnapToGrid only handles dragging/snapping, not tap events
Item-Specific Behavior: Each item widget defines its own tap handlers and visual representation
Type Safety: Pattern matching ensures correct widget creation for each item type
State Management: Grid watches the provider and updates positions through the notifier
Gesture Handling: HitTestBehavior.deferToChild in SnapToGrid allows child gestures to work
This design gives you maximum flexibility - each item type can have completely different behaviors and appearances while sharing the common snapping functionality.
// Base Item class with required properties
abstract class GridItem {
String get id;
double get width;
double get height;
Offset get position;
}
// Updated SnapToGrid that receives an Item
class SnapToGrid extends StatefulWidget {
final GridItem item;
final Widget child;
final GridInfo gridInfo;
final Function(Offset, Size, GridInfo) snapGlobalToGrid;
final Function(Offset)? onPositionChanged;
final Function(Offset)? onSnapped;
final bool enableDragging;
const SnapToGrid({
Key? key,
required this.item,
required this.child,
required this.gridInfo,
required this.snapGlobalToGrid,
this.onPositionChanged,
this.onSnapped,
this.enableDragging = true,
}) : super(key: key);
@override
_SnapToGridState createState() => _SnapToGridState();
}
class _SnapToGridState extends State<SnapToGrid>
with SingleTickerProviderStateMixin {
late Offset _position;
Offset _dragStartPosition = Offset.zero;
final GlobalKey _childKey = GlobalKey();
Size? _childSize;
bool _isDragging = false;
late AnimationController _animationController;
Animation<Offset>? _snapAnimation;
@override
void initState() {
super.initState();
_position = widget.item.position;
_animationController = AnimationController(
duration: const Duration(milliseconds: 150),
vsync: this,
);
// We can estimate size immediately from item properties
_childSize = Size(widget.item.width, widget.item.height);
// Verify actual size after render
WidgetsBinding.instance.addPostFrameCallback((_) {
_measureChild();
});
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
void _measureChild() {
final RenderBox? renderBox =
_childKey.currentContext?.findRenderObject() as RenderBox?;
if (renderBox != null && renderBox.hasSize) {
final measuredSize = renderBox.size;
// Verify measured size matches item size
assert(
(measuredSize.height - widget.item.height).abs() < 1.0,
'Measured height ${measuredSize.height} does not match item height ${widget.item.height}'
);
setState(() {
_childSize = measuredSize;
});
}
}
void _handlePanStart(DragStartDetails details) {
if (!widget.enableDragging) return;
_animationController.stop();
setState(() {
_isDragging = true;
_dragStartPosition = _position;
});
}
void _handlePanUpdate(DragUpdateDetails details) {
if (!widget.enableDragging || _childSize == null) return;
// Calculate new position
final newPosition = _dragStartPosition + details.localPosition - details.localPosition + details.localPosition - details.delta;
// Actually, we need cumulative offset
setState(() {
_position = _dragStartPosition + details.localPosition - details.localPosition + details.delta;
// Snap during drag for preview (optional)
// This shows where the widget will snap while dragging
final previewSnapPosition = widget.snapGlobalToGrid(
_position,
_childSize!,
widget.gridInfo,
);
// Apply constraints
_position = _applyConstraints(_position);
// Notify position change
widget.onPositionChanged?.call(_position);
});
}
void _handlePanEnd(DragEndDetails details) {
if (!widget.enableDragging || _childSize == null) return;
// Snap to grid on release
final snappedPosition = widget.snapGlobalToGrid(
_position,
_childSize!,
widget.gridInfo,
);
_animateToPosition(snappedPosition);
}
Offset _applyConstraints(Offset position) {
if (widget.gridInfo.gridSize == null) {
return position;
}
final maxX = widget.gridInfo.gridSize!.width - widget.item.width;
final maxY = widget.gridInfo.gridSize!.height - widget.item.height;
return Offset(
position.dx.clamp(0.0, maxX.clamp(0.0, double.infinity)),
position.dy.clamp(0.0, maxY.clamp(0.0, double.infinity)),
);
}
void _animateToPosition(Offset targetPosition) {
_snapAnimation = Tween<Offset>(
begin: _position,
end: targetPosition,
).animate(CurvedAnimation(
parent: _animationController,
curve: Curves.easeOutCubic,
));
_animationController.forward(from: 0).then((_) {
setState(() {
_position = targetPosition;
_isDragging = false;
});
widget.onSnapped?.call(targetPosition);
});
}
@override
Widget build(BuildContext context) {
Offset displayPosition;
if (_snapAnimation != null && _animationController.isAnimating) {
displayPosition = _snapAnimation!.value;
} else {
displayPosition = _position;
}
return AnimatedBuilder(
animation: _animationController,
builder: (context, _) {
return Positioned(
left: displayPosition.dx,
top: displayPosition.dy,
child: GestureDetector(
onPanStart: _handlePanStart,
onPanUpdate: _handlePanUpdate,
onPanEnd: _handlePanEnd,
behavior: HitTestBehavior.deferToChild,
child: AnimatedOpacity(
duration: const Duration(milliseconds: 100),
opacity: _isDragging ? 0.8 : 1.0,
child: Container(
key: _childKey,
child: widget.child,
),
),
),
);
},
);
}
}
// Updated ItemAGridWidget
class ItemAGridWidget extends StatelessWidget {
final ItemA item;
final GridInfo gridInfo;
final Function(Offset) onPositionChanged;
const ItemAGridWidget({
Key? key,
required this.item,
required this.gridInfo,
required this.onPositionChanged,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return SnapToGrid(
item: item, // Pass the entire item
gridInfo: gridInfo,
snapGlobalToGrid: snapGlobalToGrid,
onSnapped: onPositionChanged,
child: GestureDetector(
onTap: () {
print('ItemA ${item.id} tapped');
},
child: Container(
width: item.width,
height: item.height,
decoration: BoxDecoration(
color: item.color,
borderRadius: BorderRadius.circular(8),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
blurRadius: 4,
offset: const Offset(0, 2),
),
],
),
child: Center(
child: Icon(
Icons.star,
color: Colors.white,
size: item.width * 0.5,
),
),
),
),
);
}
Offset snapGlobalToGrid(Offset position, Size childSize, GridInfo gridInfo) {
final cellWidth = gridInfo.cellSize.width;
final cellHeight = gridInfo.cellSize.height;
return Offset(
(position.dx / cellWidth).round() * cellWidth,
(position.dy / cellHeight).round() * cellHeight,
);
}
}
Alternative: More Accurate Drag Tracking
Here's an improved version that tracks drag offset more accurately:
dart
class _SnapToGridState extends State<SnapToGrid>
with SingleTickerProviderStateMixin {
late Offset _position;
Offset _dragOffset = Offset.zero;
final GlobalKey _childKey = GlobalKey();
Size? _childSize;
bool _isDragging = false;
late AnimationController _animationController;
Animation<Offset>? _snapAnimation;
@override
void initState() {
super.initState();
_position = widget.item.position;
_animationController = AnimationController(
duration: const Duration(milliseconds: 150),
vsync: this,
);
// Use item dimensions immediately
_childSize = Size(widget.item.width, widget.item.height);
WidgetsBinding.instance.addPostFrameCallback((_) {
_verifyChildSize();
});
}
void _verifyChildSize() {
final RenderBox? renderBox =
_childKey.currentContext?.findRenderObject() as RenderBox?;
if (renderBox != null && renderBox.hasSize) {
final measuredSize = renderBox.size;
if ((_childSize!.width - measuredSize.width).abs() > 1.0 ||
(_childSize!.height - measuredSize.height).abs() > 1.0) {
print('Warning: Measured size $measuredSize differs from item size $_childSize');
setState(() {
_childSize = measuredSize;
});
}
}
}
void _handlePanStart(DragStartDetails details) {
if (!widget.enableDragging) return;
_animationController.stop();
setState(() {
_isDragging = true;
_dragOffset = Offset.zero;
});
}
void _handlePanUpdate(DragUpdateDetails details) {
if (!widget.enableDragging || _childSize == null) return;
setState(() {
// Accumulate drag offset
_dragOffset += details.delta;
// Calculate current position
final currentPosition = _position + _dragOffset;
// Live snapping preview (optional)
// You can show a preview of where it will snap
final previewSnap = widget.snapGlobalToGrid(
currentPosition,
_childSize!,
widget.gridInfo,
);
// Apply constraints to keep within bounds
final constrainedPosition = _applyConstraints(currentPosition);
_dragOffset = constrainedPosition - _position;
// Notify parent of current dragged position
widget.onPositionChanged?.call(constrainedPosition);
});
}
void _handlePanEnd(DragEndDetails details) {
if (!widget.enableDragging || _childSize == null) return;
// Calculate final position
final currentPosition = _position + _dragOffset;
// Snap to grid
final snappedPosition = widget.snapGlobalToGrid(
currentPosition,
_childSize!,
widget.gridInfo,
);
// Animate to snapped position
_animateToPosition(snappedPosition);
}
Offset _applyConstraints(Offset position) {
if (widget.gridInfo.gridSize == null) {
return position;
}
// Use item dimensions for constraints
final maxX = widget.gridInfo.gridSize!.width - widget.item.width;
final maxY = widget.gridInfo.gridSize!.height - widget.item.height;
return Offset(
position.dx.clamp(0.0, maxX.clamp(0.0, double.infinity)),
position.dy.clamp(0.0, maxY.clamp(0.0, double.infinity)),
);
}
void _animateToPosition(Offset targetPosition) {
final startPosition = _position + _dragOffset;
_snapAnimation = Tween<Offset>(
begin: startPosition,
end: targetPosition,
).animate(CurvedAnimation(
parent: _animationController,
curve: Curves.easeOutCubic,
));
_animationController.forward(from: 0).then((_) {
setState(() {
_position = targetPosition;
_dragOffset = Offset.zero;
_isDragging = false;
});
widget.onSnapped?.call(targetPosition);
});
}
@override
Widget build(BuildContext context) {
Offset displayPosition;
if (_snapAnimation != null && _animationController.isAnimating) {
displayPosition = _snapAnimation!.value;
} else {
displayPosition = _position + _dragOffset;
}
return AnimatedBuilder(
animation: _animationController,
builder: (context, _) {
return Positioned(
left: displayPosition.dx,
top: displayPosition.dy,
child: GestureDetector(
onPanStart: _handlePanStart,
onPanUpdate: _handlePanUpdate,
onPanEnd: _handlePanEnd,
behavior: HitTestBehavior.deferToChild,
child: AnimatedOpacity(
duration: const Duration(milliseconds: 100),
opacity: _isDragging ? 0.8 : 1.0,
child: Container(
key: _childKey,
child: widget.child,
),
),
),
);
},
);
}
}
Key Features
Item-Based: SnapToGrid receives the Item object and uses its dimensions
Immediate Size: Uses item.width and item.height immediately, verifies after render
Integrated GestureDetector: Handles all drag gestures internally
Snapping in onPanUpdate: Has access to child size for snapping calculations
Accurate Position Tracking: Uses drag offset for smooth dragging
The widget now has all the information it needs (item dimensions) to perform snapping during drag operations.