Offset vs Alignment in Flutter

Viewed 1125

Although I know their uses and properties but sometimes I found it hard to tell the difference between Offset and Alignment as both of them represents a point in x-axis and y-axis

2 Answers

Offset uses coordinates for the object's location. Alignment on the other hand still uses coordinates, but Parent widgets is used as the basis for the coordinates.

For others out there: According to https://api.flutter.dev/flutter/painting/Alignment-class.html, The equation for alignment to offset is:

offsetX = alignmentX * width/2 + width/2
offsetY = alignmentY * height/2 + height/2

So using some algebra, to go the other way and convert an offset to an alignment is:

alignmentX = (offsetX - width/2)/(width/2)
alignmentY = (offsetY - height/2)/(height/2)

Where width and height is the width/height of the parent the offset is based on (like the window/screen if using global coordinates)

Related