Calculate distance between points on the screen in Flutter, independent of screen size

Viewed 295

I am building an app to track distance between 2 points on a football field.

I know how long a field is in reality, let's say 100 meters for convenience. I want to be able to measure a distance between 2 points, regardless of screen size (it needs to be translated to real measurements, such as meters or yards).

The image asset will be set as background for a Container. Currently, I can track the location of the points where I place the initial position and the final position, but this only translates in X and Y coordinates, as per my screen.

How can I make this measurement independent of the screen and convert it to meters accurately and consistently, regardless of the device used?

Thanks!

enter image description here

1 Answers

Simple way of finding distance between Offset is like

(_goalKeeper! - _playerOffset!).distance.

For responsive UI I am using LayoutBuilder

class _TState extends State<T> {
  Offset? _goalKeeper;
  Offset? _playerOffset;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: LayoutBuilder(
        builder: (context, constraints) {
          return GestureDetector(
            onPanUpdate: (details) {
              // you can choose others method like tapDown etc that will provide details
              //* goal keeper point
              _goalKeeper =
                  Offset(constraints.maxWidth / 2, 0); // top center point

              // global or local depends on code-structure check offical doc for more
              _playerOffset =
                  Offset(details.localPosition.dx, details.localPosition.dy);

              setState(() {});
            },
            child: Container(
              // full body will take touch event
              color: Colors.green,
              child: Stack(
                children: [
                  const Align(
                    alignment: Alignment.topCenter,
                    child: Icon(Icons.ac_unit),
                  ),
                  if (_playerOffset != null)
                    Text(
                        "distance ${(_goalKeeper! - _playerOffset!).distance}"),
                  if (_playerOffset != null)
                    Positioned(
                        left: _playerOffset!.dx,
                        top: _playerOffset!.dy,
                        child: Icon(Icons.person))
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}
Related