Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do detect where a user tapped on my screen, with Flutter?

Tags:

flutter

dart

I'd like to know the x/y coordinates of where a tap occurred on my screen. I found the GestureDetector, but it doesn't seem to tell me where exactly the tap took place.

Here's my code so far:

import 'package:flutter/material.dart';

void main() {
  runApp(new MyWidget());
}

class MyWidget extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
      onTap: () => print('tapped!')
    );
  }
}

Which does register a tap... but how do I found out where the tap started from?

like image 946
Seth Ladd Avatar asked Jun 14 '17 03:06

Seth Ladd


People also ask

How do you detect tap in Flutter?

Use GestureDetector's behavior property and pass HitTestBehavior. opaque to it, which recognizes entire screen and detects the tap when you tap anywhere on the screen.

How do you use tap in Flutter?

Solution to that is to create an InkWell inside the Card . return Card( child: InkWell( child: Row( // Row content ), onTap: () => { print("Card tapped."); }, ), elevation: 2, ); This will help you gain the ripple effect and perform the tap captures on Android too.

What is GestureDetector widget?

A widget that detects gestures. Attempts to recognize gestures that correspond to its non-null callbacks. If this widget has a child, it defers to that child for its sizing behavior.


1 Answers

Observe onTapDown and onTapUp, they provide more details for you to work with.

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new GestureDetector(
      onTap: () => print('tapped!'),
      onTapDown: (TapDownDetails details) => _onTapDown(details),
      onTapUp: (TapUpDetails details) => _onTapUp(details),
    );
  }

  _onTapDown(TapDownDetails details) {
    var x = details.globalPosition.dx;
    var y = details.globalPosition.dy;
    // or user the local position method to get the offset
    print(details.localPosition);
    print("tap down " + x.toString() + ", " + y.toString());
  }

  _onTapUp(TapUpDetails details) {
    var x = details.globalPosition.dx;
    var y = details.globalPosition.dy;
    // or user the local position method to get the offset
    print(details.localPosition);
    print("tap up " + x.toString() + ", " + y.toString());
  }
}
like image 171
Brandon Avatar answered Oct 06 '22 09:10

Brandon