In Flutter if you wanna get the x and y position or get tap position, you may use GestureDetector widget. It provides onTapDown property which takes a function.
This could be used for Gaming tap position
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,
theme: ThemeData(
primarySwatch: Colors.deepOrange,
),
home: const TapPosition(),
);
}
}
class TapPosition extends StatefulWidget {
const TapPosition({Key? key}) : super(key: key);
@override
State<TapPosition> createState() => _TapPositionState();
}
class _TapPositionState extends State<TapPosition> {
Offset? _tapPosition;
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('Tap Position')),
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: [
Text(
'X: ${_tapPosition?.dx.toStringAsFixed(2) ?? "Tap Somewhere"}',
style: const TextStyle(fontSize: 36, color: Colors.white),
),
const SizedBox(
height: 20,
),
Text(
'Y: ${_tapPosition?.dy.toStringAsFixed(2) ?? "Tap Somewhere"}',
style:
const TextStyle(fontSize: 36, color: Colors.yellow),
),
],
),
),
const SizedBox(
height: 30,
),
Center(
child: ElevatedButton(
onPressed: () =>
ScaffoldMessenger.of(context).showSnackBar( SnackBar(
content: Text(
'${_tapPosition?.dx.toStringAsFixed(2)} '
'/ ${_tapPosition?.dy.toStringAsFixed(2)}'
),
)),
child: const Text('A game button')),
),
],
),
),
),
);
}
}