tabIndexFromGlobalPosition static method
int
tabIndexFromGlobalPosition(
- Offset globalPosition,
- BuildContext context,
- int itemCount, {
- Axis direction = Axis.horizontal,
Converts a global tap position to a tab index using the raw (un-remapped) position fraction.
Unlike getAlignmentFromGlobalPosition, this method does not apply
the indicator-center padding/draggable-range remap. It divides the bar
into itemCount equal slices and returns which slice contains the tap.
Use this for discrete tap-to-index conversions (e.g. onTapDown).
Use getAlignmentFromGlobalPosition for continuous drag tracking
where the indicator center must stay within its physical travel range.
Parameters:
globalPosition: The global position from tap/pointer detailscontext: Build context used to find the render boxitemCount: Total number of items (tabs)direction: Axis along which the bar is laid out (default: horizontal)
Returns: The item index (0-based, clamped to 0, itemCount-1).
Example:
// 400-px wide bar with 4 tabs (each 100 px):
// tap at x=310 → rawRelativeX=0.775 → (0.775 * 4).floor() = 3
final index = DraggableIndicatorPhysics.tabIndexFromGlobalPosition(
globalPosition, context, 4,
);
Implementation
static int tabIndexFromGlobalPosition(
Offset globalPosition,
BuildContext context,
int itemCount, {
Axis direction = Axis.horizontal,
}) {
final box = context.findRenderObject()! as RenderBox;
final localPosition = box.globalToLocal(globalPosition);
final mainPosition =
direction == Axis.horizontal ? localPosition.dx : localPosition.dy;
final mainExtent =
direction == Axis.horizontal ? box.size.width : box.size.height;
final rawRelativeX = (mainPosition / mainExtent).clamp(0.0, 1.0);
return (rawRelativeX * itemCount).floor().clamp(0, itemCount - 1);
}