Flutter: Get the Position of a Tap (X & Y coordinates)

Last updated on August 12, 2022 A Goodman Loading... Post a comment

This short and straightforward article shows you how to get the location (X and Y coordinates) of a tap in Flutter.

The TLDR

What you need to do is to wrap your entire screen (or a certain area) within a GestureDetector widget and listen to the onTapDown or onTapUp event, like this:

GestureDetector(
      onTapDown: (details){
         final tapPosition = details.globalPosition;
         final x = tapPosition.dx;
         final y = tapPosition.dy;
         // do something with x & y
      },
      child: Scaffold(/* ...*/)
)

Note that the action of getting tap location doesn’t prevent the user from interacting with other widgets like buttons, forms, etc. For more clarity, see the full example below.

The Example

App Preview

This demo captures the tap location (where the user’s finger hits the screen) then presents the results on the screen:

The Code

The complete code in main.dart with explanations in the comments:

// kindacode.com
// main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'KindaCode.com',
      theme: ThemeData(
        primarySwatch: Colors.amber,
      ),
      home: const KindaCodeDemo(),
    );
  }
}

class KindaCodeDemo extends StatefulWidget {
  const KindaCodeDemo({Key? key}) : super(key: key);

  @override
  State<KindaCodeDemo> createState() => _KindaCodeDemoState();
}

class _KindaCodeDemoState extends State<KindaCodeDemo> {
  // the tap location
  Offset? _tapPosition;

  // this function is called when the user taps somewhere on the screen
  void _getTapPosition(TapDownDetails details) async {
    final tapPosition = details.globalPosition;
    setState(() {
      _tapPosition = tapPosition;
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapDown: (details) => _getTapPosition(details),
      child: Scaffold(
        appBar: AppBar(title: const Text('KindaCode.com')),
        body: Padding(
          padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 15),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                width: double.infinity,
                height: 200,
                color: Colors.blue,
                padding: const EdgeInsets.all(20),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // Display X coordinate of tap
                    Text(
                      'X: ${_tapPosition?.dx.toStringAsFixed(2) ?? "Tap Somewhere"}',
                      style: const TextStyle(fontSize: 36, color: Colors.white),
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    // Display Y coordinate of tap
                    Text(
                      'Y: ${_tapPosition?.dy.toStringAsFixed(2) ?? "Tap Somewhere"}',
                      style:
                          const TextStyle(fontSize: 36, color: Colors.yellow),
                    ),
                  ],
                ),
              ),

              // the action of getting tap location doesn't prevent user from interacting with other widgets like buttons, forms, etc.
              // the purpose of the button below is to demonstrate that
              const SizedBox(
                height: 30,
              ),
              ElevatedButton(
                  onPressed: () =>
                      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
                        content: Text('Hi There'),
                      )),
                  child: const Text('A Useless Button')),
            ],
          ),
        ),
      ),
    );
  }
}

Conclusion

You’ve learned how to determine the X and Y coordinates of the hitting point of a tap. Continue exploring more new and fascinating stuff in the modern Flutter world by taking a look at the following articles:

You can also tour around our Flutter topic page or Dart topic page for the most recent tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles